property 中的strong 与weak
来源:互联网 发布:mac实用工具 编辑:程序博客网 时间:2024/05/20 16:01
strong关键字与retain关似,用了它,引用计数自动+1,用实例更能说明一切
@property (nonatomic, strong) NSString *string1;
@property (nonatomic, strong) NSString *string2;
有这样两个属性,
@synthesize string1;
@synthesize string2;
猜一下下面代码将输出什么结果?
self.string1 = @"String 1";
self.string2 = self.string1;
self.string1 = nil;
NSLog(@"String 2 = %@", self.string2);
结果是:String 2 = String 1
由于string2是strong定义的属性,所以引用计数+1,使得它们所指向的值都是@"String 1", 如果你对retain熟悉的话,这理解并不难。
接着我们来看weak关键字:
如果这样声明两个属性:
@property (nonatomic, strong) NSString *string1;
@property (nonatomic, weak) NSString *string2;
并定义
@synthesize string1;
@synthesize string2;
再来猜一下,下面输出是什么?
self.string1 = @"String 1";
self.string2 = self.string1;
self.string1 = nil;
NSLog(@"String 2 = %@", self.string2);
结果是:String 2 = null
分析一下,由于self.string1与self.string2指向同一地址,且string2没有retain内存地址,
而self.string1=nil释放了内存,所以string1为nil。
声明为weak的指针,指针指向的地址一旦被释放,这些指针都将被赋值为nil。
这样的好处能有效的防止野指针。在c/c++开发过程中,为何大牛都说指针的空间释放了后,
都要将指针赋为NULL. 在这儿用weak关键字帮我们做了这一步。
- property 中的strong 与weak
- property 中的strong 与weak
- property 中的strong 与weak
- @property 中的strong 与weak
- property 中的strong 与weak
- property 中的strong 与weak
- property 中的strong 与weak
- property 中的strong 与weak
- property 中的strong 与weak
- property 中的strong 与weak的区别
- property 中的strong 与weak,assign
- iOS - property中的strong与weak
- iOS property strong/weak
- property中的strong 、weak、copy 、assign 、retain 、unsafe_unretained 与autoreleasing区别和作用详解
- property中的strong 、weak、copy 、assign 、retain 、unsafe_unretained 与autoreleasing区别和作用详解
- property中的strong 、weak、copy 、assign 、retain 、unsafe_unretained 与autoreleasing区别和作用详解
- property中的strong 、weak、copy 、assign 、retain 、unsafe_unretained 与autoreleasing区别和作用详解
- property中的strong 、weak、copy 、assign 、retain 、unsafe_unretained 与autoreleasing区别和作用详解
- Hadoop版本说明
- 今天被一个无where条件的SQL搞的内存不足了
- 电压传感器是什么?
- 如何使用GParted调整Linux分区(图解,双语)
- find命令详解
- property 中的strong 与weak
- 华为JAVA面试题
- shell 脚本 与 shell 脚本的编写
- C语言中的关键字
- 324234
- java小练习---进制之间的转换
- android xml中转义字符的使用
- 关于一些简单的控件
- java日期格式化中的MM和mm