文章出處
文章列表
ARC是什么:
1.ARC是編譯器特性,而不是運行時特性;
2.ARC不是其他語言中的垃圾回收,有著本質區別;
ARC的優點:
1.完全消除了手動管理內存的煩瑣;
2.基本上能避免內存泄露;
3.有時還能更加快速,因為編譯器還可以執行某些優化;
ARC的判斷準則:
只要沒有強指針指向對象,對象都會被釋放,(默認情況下所有的指針都是強指針)
強指針(__strong) 弱指針(__weak)
1 int main(int argc, const char * argv[]) { 2 @autoreleasepool { 3 Person *p =[[Person alloc] init]; 4 p=nil;//執行完這行釋放p 5 6 __strong Person *p1 = [[Person alloc] init]; 7 __weak Person *p2 = p1; 8 }//在這行釋放p2 9 return 0; 10 }
弱指針,在剛創建完就會被釋放。(不要把一個剛剛創建的對象給一個弱指針)
當兩個對象互相引用的時候,會出現循環引用,在ARC中的解決辦法是:
一個用strong,一個用weak;
Person.h:
#import <Foundation/Foundation.h> @class Dog; @interface Person : NSObject @property(nonatomic,strong)Dog *dog; @end
Person.m:
#import "Person.h" @implementation Person - (void)dealloc { NSLog(@"person dealloc"); } @end
Dog.h:
#import <Foundation/Foundation.h> @class Person; @interface Dog : NSObject @property(nonatomic,weak)Person * person; @end
Dog.m:
#import "Dog.h" @implementation Dog - (void)dealloc { NSLog(@"dog dealloc"); } @end
main.m:
Person * p =[[Person alloc] init]; Dog * dog = [[Dog alloc] init]; p.dog = dog; dog.person = p;
這樣處理之后最后就可以全部釋放了:
文章列表
全站熱搜