iOS 开发之 strong 和 weak 介绍
有开发
ios5 之前的版本的童鞋就知道在 ios5 以上(ios5 不行,而且关键字 weak 没有提
示,敲出来不会报错
)的属性设置多了 strong 和 weak 这两个东东。有啥用呢有啥区别呢。简
单的说呢就是为了支持
ARC 模式而生的(what's the ARC?that's right,here is the answer:代码中
自动加入了
retain/release,原先需要手动添加的用来处理内存管理的引用计数的代码可以自
动地由编译器完成了,可以了吧
!!!)。下面单独来讲下两个关键字:
1.strong(与 retain 作用类似,可以说是用来代替 retain),下面代码说明一下:
@property (nonatomic, strong) NSString *tempStr1;
@property (nonatomic, strong) NSString *tempStr2;
然后声明一下:
@synthesize tempStr1;
@synthesize tempStr2;
然后赋值调用:
self.tempStr1 = @"hello World";
self.tempStr2 = self.tempStr1;
self.tempStr1 = nil;
NSLog(@"tempStr2 = %@", self.tempStr2);
运行结果:
tempStr2 = hello World
2.weak(观察下与 strong 的区别):
@property (nonatomic, strong) NSString *tempStr1;
@property (nonatomic, weak) NSString *tempStr2;
然后声明一下:
@synthesize tempStr1;
@synthesize tempStr2;
然后赋值调用:
self.tempStr1 = [[NSString alloc] initWithUTF8String:"hello World"];
self.tempStr2 = self.tempStr1;
self.tempStr1 = nil;
NSLog(@"tempStr2 = %@", self.tempStr2);