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
原创粉丝点击