標籤:objective arc arc特點與判斷準則 自動引用技術
ARC特點與判斷準則
/* ARC的判斷準則:只要沒有強指標指向對象,就會釋放對象 1.ARC特點 1> 不允許調用release、retain、retainCount 2> 允許重寫dealloc,但是不允許調用[super dealloc] 3> @property的參數 * strong :成員變數是強指標(適用於OC物件類型) * weak :成員變數是弱指標(適用於OC物件類型) * assign : 適用於非OC物件類型 4> 以前的retain改為用strong 指標分2種: 1> 強指標:預設情況下,所有的指標都是強指標 __strong 2> 弱指標:__weak */int main(){ Dog *d = [[Dog alloc] init]; Person *p = [[Person alloc] init]; p.dog = d; d = nil; NSLog(@"%@", p.dog); return 0;}void test(){ // 錯誤寫法(沒有意義的寫法) __weak Person *p = [[Person alloc] init]; NSLog(@"%@", p); NSLog(@"------------");}
@class Dog;@interface Person : NSObject@property (nonatomic, strong) Dog *dog;@property (nonatomic, strong) NSString *name;@property (nonatomic, assign) int age;@end
@implementation Person- (void)dealloc{ NSLog(@"Person is dealloc"); // [super dealloc];}@end
@interface Dog : NSObject@end
@implementation Dog- (void)dealloc{ NSLog(@"Dog is dealloc");}@end
ARC循環參考問題
/** * 當兩端循環參考的時候,解決方案: 1> ARC 1端用strong,另1端用weak 2> 非ARC 1端用retain,另1端用assign */int main(){ Person *p = [[Person alloc] init]; Dog *d = [[Dog alloc] init]; p.dog = d; d.person = p; return 0;}
@class Dog;@interface Person : NSObject@property (nonatomic, strong) Dog *dog;@end
@implementation Person- (void)dealloc{ NSLog(@"Person--dealloc");}@end
@class Person;@interface Dog : NSObject@property (nonatomic, weak) Person *person;@end
@implementation Dog- (void)dealloc{ NSLog(@"Dog--dealloc");}@end
Objective-C - ARC(Automatic Reference Counting)自動引用技術詳解