-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcopy_retain.m
94 lines (66 loc) · 1.64 KB
/
copy_retain.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#import <Foundation/Foundation.h>
#include <stdio.h>
volatile int refBarCounter = 0;
volatile int totalBarInits = 0;
volatile int refFooCounter = 0;
volatile int totalFooInits = 0;
@interface Bar : NSObject<NSCopying>
@end
@implementation Bar
- (instancetype) init {
self = [super init];
printf("Bar::init\n");
++totalBarInits;
++refBarCounter;
return self;
}
-(instancetype)copyWithZone: (NSZone *)_ {
return [[self class] new];
}
- (void) dealloc {
[super dealloc];
printf("Bar::dealloc\n");
--refBarCounter;
}
@end
@interface Foo : NSObject
//@property(nonatomic, assign) Bar* propbar; // Does nothing. YOLO
@property(nonatomic, copy) Bar* propbar; // You must release
//@property(nonatomic, retain) Bar* propbar; // You must release
@end
@implementation Foo
- (instancetype) init {
// NSObject isn't going to fail... is it?
self = [super init];
printf("Foo::init\n");
++refFooCounter;
++totalFooInits;
return self;
}
-(void) hello {
printf("hello!\n");
}
- (void) dealloc {
printf("Foo::dealloc\n");
// Both are basically the same.
[self.propbar release];
--refFooCounter;
[super dealloc];
}
@end
int main() {
@autoreleasepool {
Foo* feh = [[Foo new] autorelease];
Foo* foo = [Foo new];
Bar* bar = [[Bar new] autorelease];
foo.propbar = bar;
printf("Assigning nil to propbar\n");
foo.propbar = nil;
printf("Assigning new Bar to propbar\n");
foo.propbar = [[Bar new] autorelease];
[foo release];
}
printf("Leaked %d/%d Foo instances.\n", refFooCounter, totalFooInits);
printf("Leaked %d/%d Bar instances.\n", refBarCounter, totalBarInits);
// assert(refFooCounter == refBarCounter == 0)
}