Object Copying语法 第八课
来源:互联网 发布:前十月中国经济数据 编辑:程序博客网 时间:2024/06/04 17:54
Copy和MutableCopy
1, NSString(NSMutableString),NSArray(NSMutableArray),NSSet(NSMutableSet),NSDictionary(NSMutbleDictionary)的复制和动态复制
这几个的用法都是一样的,下面举一个NSString的用法。copy的目的就是拷贝生成一个新对象,改变新对象的值时保持原对象不变
void teststringCopy(){NSString *string = [[NSString alloc] initWithFormat:@"the age is:%i",10];//浅拷贝(指针拷贝),不会生成一个新的对象,str1和string都是指向同一个对象,实际上是做一次retain操作。(str1 == string),源对象的计数器+1//其实为了性能着想,copy直接返回原对象本身NSString *str1 = [string copy];//深拷贝生成一个新对象,原对象的计数器不变(str2 != string)NSMutableString str2 = [string mutableCopy];NSMutableString *string2 = [[NSMutableString alloc] initWithFormat:@"the age is:%i",10];//浅深拷贝生成一个新对象,原对象的计数器不变NSString *str1 = [string2 copy];//深拷贝生成一个新对象,原对象的计数器不变NSMutableString str2 = [string2 mutableCopy]; }
2,自定义对象和成员变量拷贝
@interface Student : NSObject<NSCopying>//copy:调用set方法时把旧的对象release,把新的对象做一次copy操作,改变外部变量的值内部变量不变//retain:调用set方法时把旧对象release,把新对象做一次retain操作,改变外部变量的值内部变量跟着变//一般开发中NSString用copy,其他一般用retain@property (nonatomic,copy) NSString *name;+(id) studentWithName:(NSString *)name;@end@implementation Student+(id) studentWithName:(NSString *)name{//这里最好写self class不写StudentStudent *stu = [[[[self class] alloc]init] autorelease];stu.name = name;return stu;}//coping协议方法,只有实现这个方法,student才能使用copy方法//这里创建副本对象不要求释放,需要外部释放,这个是内存管理的一个特殊地方-(id) copyWithZone:(NSZone *)zone{Student *copy = [[[[self class] allocWithZone:zone] init];copy.name = self.name;return copy;}@end@interface GoodStudent : Student@property (nonatomic,assign) int age;+(id) goodStudentWithAge:(int)age name:(NSString *)name;@end@implementation GoodStudent+(id) goodStudentWithAge:(int) age{//这个地方用self class,而不能用GoodStudent,因为GoodStudent没有studentWithName方法GoodStudent *good = [[self class] studentWithName:name];good.age = age;return good;}@endvoid testNameCopy(){// 测试成员变量的拷贝Student *stu = [[[Student alloc] init] autorelease];NSMutableString *string = [NSMutableString stringWithFormat:@"the age is:%@",10];stu.name = string;[string appendString:@" abcd"];//测试结果name != string}void testStuCopy(){Student *stu1 = [Student studentWithName:@"stu1"];Student *stu2 = [stu1 copy];stu2.name = @"stu2";//stu1 != stu2}
0 0
- Object Copying语法 第八课
- Object ARC语法 第九课
- c++ Blocking Undesirable Object Copying and Implicit Conversions
- Object-c基本语法
- object-c 语法
- object c语法速成
- object c语法速成
- object-c语法基础
- Object-C 块语法
- Object C 语法
- Object-c基础语法
- object-c语法小计
- Object C 语法入门
- Object-c------语法预览
- Object-C block语法
- uva714 - Copying Books 入门经典II 第八章 例题8-10
- object-c --语法系列(一)
- 第一章.Object-c基本语法
- J2SE之简介
- Errors running builder 'DeploymentBuilder' on project_java
- 两分钟彻底让你明白Android Activity生命周期(图文)!
- Ubuntu下安装和配置Apache2
- Python的高级特性
- Object Copying语法 第八课
- Mysql学习-(1- Ubuntu Linux下安装MySQL)
- 相册循环播放(提出导航条的影响)
- <转>编译原理学习导论
- 如果使用Jquery创建Win8风格的色块超链接
- dnsmasq配置域名重定向和dns缓存
- 如何让Grid单元格中的内容超长时自动换行显示?
- 架构设计—数据库的性能与建模
- MySQL常用SQL语句