- 定义copy和strong的字符串属性
@interface ViewController ()
@property (nonatomic, copy) NSString * strCopy;
@property (nonatomic, strong) NSString * strStrong;
@end
NSMutableString *originString = [NSMutableString stringWithFormat:@"我是可变的源数据字符串"];
self.strCopy = originString;
self.strStrong = originString;
[originString appendFormat:@"_append"];
NSLog(@"originString = %@ address = %p self.strCopy = %@ address = %p self.strStrong = %@ address = %p",originString,originString,self.strCopy,self.strCopy,self.strStrong,self.strStrong);
- 打印结果
originString = 我是可变的源数据字符串_append address = 0x170269980
self.strCopy = 我是可变的源数据字符串 address = 0x170240a20
self.strStrong = 我是可变的源数据字符串_append address = 0x170269980
- 用copy修饰属性的类型修改为NSMutableString,再对改属性进行append操作会报错:
@interface ViewController ()
@property (nonatomic, copy) NSMutableString * strCopy;
@property (nonatomic, strong) NSString * strStrong;
@end
NSMutableString *originString = [NSMutableString stringWithFormat:@"我是可变的源数据字符串"];
self.strCopy = originString;
self.strStrong = originString;
[originString appendFormat:@"_append"];
[self.strCopy appendFormat:@"212"];
NSLog(@"originString = %@ address = %p self.strCopy = %@ address = %p self.strStrong = %@ address = %p",originString,originString,self.strCopy,self.strCopy,self.strStrong,self.strStrong);
实际上执行的self.strCopy
的set点方法为:
- (void)setStrCopy:(NSMutableString *)strCopy{
//[strCopy copy]产生了不可变的字符串
_strCopy = [strCopy copy];
}