规范上NSString做属性都是写成copy的,理论上应该是复制了字符串而不是单纯的增加引用计数,其实问题只会出现在把NSMutableString赋值给NSString的时候。
首先做以下几个变量声明:
@property (retain, nonatomic) NSString *retainStr;
@property (copy, nonatomic) NSString *copyStr;
@property (retain, nonatomic) NSMutableString *retainMStr;
@property (copy, nonatomic) NSMutableString *copyMStr;
实现代码如下:
NSMutableString *mStr = [NSMutableString string];
[mStr setString:@"我没变"];
self.retainStr = mStr;
self.copyStr = mStr;
self.retainMStr = mStr;
self.copyMStr = mStr;
NSLog(@"retainStr:%@", self.retainStr);
NSLog(@"copyStr:%@", self.copyStr);
NSLog(@"retainMStr:%@", self.retainMStr);
NSLog(@"copyMStr:%@", self.copyMStr);
NSLog(@" ");
[mStr setString:@"我变了"];
NSLog(@"retainStr:%@", self.retainStr);
NSLog(@"copyStr:%@", self.copyStr);
NSLog(@"retainMStr:%@", self.retainMStr);
NSLog(@"copyMStr:%@", self.copyMStr);
NSLog(@" ");
NSString *str = @"我来了";//[[NSString alloc] initWithFormat:@"我来了"];//两种方式都一样。
self.retainStr = str;
self.copyStr = str;
self.retainMStr = [str mutableCopy];
self.copyMStr = [str mutableCopy];
NSLog(@"retainStr:%@", self.retainStr);
NSLog(@"copyStr:%@", self.copyStr);
NSLog(@"retainMStr:%@", self.retainMStr);
NSLog(@"copyMStr:%@", self.copyMStr);
NSLog(@" ");
str =@"我走了";//[[NSStringalloc] initWithFormat:@"我走了"];//两种方式都一样
NSLog(@"retainStr:%@", self.retainStr);
NSLog(@"copyStr:%@", self.copyStr);
NSLog(@"retainMStr:%@", self.retainMStr);
NSLog(@"copyMStr:%@", self.copyMStr);
NSLog(@" ");
打印结果如下:
2012-10-12 13:53:14.858 StringDemo[1515:11303] retainStr:我没变
2012-10-12 13:53:14.860 StringDemo[1515:11303] copyStr:我没变
2012-10-12 13:53:14.861 StringDemo[1515:11303] retainMStr:我没变
2012-10-12 13:53:14.862 StringDemo[1515:11303] copyMStr:我没变
2012-10-12 13:53:14.863 StringDemo[1515:11303]
2012-10-12 13:53:14.864 StringDemo[1515:11303] retainStr:我变了
2012-10-12 13:53:14.865 StringDemo[1515:11303] copyStr:我没变
2012-10-12 13:53:14.866 StringDemo[1515:11303] retainMStr:我变了
2012-10-12 13:53:14.867 StringDemo[1515:11303] copyMStr:我没变
2012-10-12 13:53:14.868 StringDemo[1515:11303]
2012-10-12 13:53:14.869 StringDemo[1515:11303] retainStr:我来了
2012-10-12 13:53:14.869 StringDemo[1515:11303] copyStr:我来了
2012-10-12 13:53:14.870 StringDemo[1515:11303] retainMStr:我来了
2012-10-12 13:53:14.871 StringDemo[1515:11303] copyMStr:我来了
2012-10-12 13:53:14.872 StringDemo[1515:11303]
2012-10-12 13:53:14.873 StringDemo[1515:11303] retainStr:我来了
2012-10-12 13:53:14.874 StringDemo[1515:11303] copyStr:我来了
2012-10-12 13:53:14.875 StringDemo[1515:11303] retainMStr:我来了
2012-10-12 13:53:14.876 StringDemo[1515:11303] copyMStr:我来了
web学习笔记二
java Web 学习笔记一
简述Bootstrap栅格布局方式
CSS3笔记
CSS 笔记
初识HTML流水笔记
数据库初识
java流的操作
Java 套接字使用