- #import "ViewController.h"
- @interface ViewController ()
- @property (nonatomic, weak) UIView *weakView;
- @property (nonatomic, weak) UIView *selfWeakView;
- @property (nonatomic, strong) UIView *strongView;
- @property (nonatomic, strong) UIView *selfStrongView;
- @end
- @implementation ViewController
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- self.selfStrongView = [[UIView alloc]initWithFrame:CGRectMake(25, 25, 50, 50)];
- printf("self.selfStrongViewretain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(self.selfStrongView)));
- [self.view addSubview:self.selfStrongView];
- printf("self.selfStrongView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(self.selfStrongView)));
- _strongView = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 50, 50)];
- printf("_strongView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(_strongView)));
- [self.view addSubview:self.strongView];
- printf("_strongView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(_strongView)));
- UIView *selfView = [[UIView alloc]initWithFrame:CGRectMake(150, 150, 50, 50)];
- self.selfWeakView = selfView;
- printf("self.selfWeakView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(self.selfWeakView)));
- [self.view addSubview:self.selfWeakView];
- printf("self.selfWeakView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(self.selfWeakView)));
- UIView *weaksView = [[UIView alloc]initWithFrame:CGRectMake(200, 200, 50, 50)];
- printf("weakView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(weaksView)));
- _weakView = weaksView;
- printf("_weakView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(_weakView)));
- [self.view addSubview:_weakView];
- printf("_weakView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(_weakView)));
- }
- - (void)viewWillAppear:(BOOL)animated
- {
- printf("self.selfStrongView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(_strongView)));
- printf("_strongView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(_strongView)));
- printf("self.selfWeakView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(self.selfWeakView)));
- printf("_weakView retain count = %ld\n",CFGetRetainCount((__bridge CFTypeRef)(_weakView)));
- }
- @end
在ARC中,對象釋放的最終根據還是根據引用計數為0時去釋放。而weak與strong的根本差別是在set方法中,weak的set方法和strong的set方法都是釋放舊值保留新值,但是weak的set方法會對其autorelease,即延遲release一次,而strong的set方法也是釋放舊值保留新值,但是其不會延遲release。最終效果是strong會+1,weak不會+1.
要注意,用_去指派的時候是不調用set方法的,也就是說無論weak還是strong,隻要用_指派都不會對引用計數加1,差別在于self.文法會調用set方法,strong的self.會調用set方法+1.而weak的_和self.文法都不會+1.
是以,建議用weak,用weak時無論用_和.文法都不會導緻+1。用strong時用self.文法會導緻+1.建議用weak。同時weak在對象回收以後可以将對象指針置成nil。