上次说到copy,现在来说说strong,先上代码
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, copy) NSString* stringCopy;
@property (nonatomic, strong) NSString* stringStrong;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString* string = @"这是一个测试的的string,一般由服务器返回";
NSLog(@"%p====%p=====%p", string, self.stringCopy, self.stringStrong);
self.stringCopy = string;
self.stringStrong = string;
NSLog(@"%p====%p=====%p", string, self.stringCopy, self.stringStrong);
string = @"我们现在修改该string";
NSLog(@"%p====%p=====%p", string, self.stringCopy, self.stringStrong);
NSLog(@"string:%@---self.stringCopy:%@----self.stringStrong%@", string, self.stringCopy, self.stringStrong);
}
@end
接下来看看输出的值
0x106070078====0x0=====0x0
0x106070078====0x106070078=====0x106070078
0x1060700b8====0x106070078=====0x106070078
string:我们现在修改该string---self.stringCopy:这是一个测试的的string,一般由服务器返回----self.stringStrong这是一个测试的的string,一般由服务器返回
这种情况下呢,copy与strong修饰的对象,最终在string修改后是保持不变的,所以,这时候copy与strong修饰都是可以的,可以说没有区别
以下是个人的理解,如果有说的不对的还望理解
假设有一个NSString对象A,我们通过B对象对A进行赋值操作
1.如果B是可变类型,那么使用copy对A进行修饰是安全的,且是非常必要的,千万不要使用strong对A进行修饰,因为这种情况下,B如果发生改变,那么A就会随之改变
2.如果B是不可变类型,那么使用copy与strong对A进行修饰,最终的结果是完全一样的,B发生变化不会影响到A
网友评论