#pragma mark 演示字符串的copy //深拷贝--对象拷贝--内容拷贝(产生新对象)新对象计数器+1,原对象不变 void stringmutableCopy(){ //string = 1 NSString *string = [[NSString alloc]initWithFormat:@"age is %i", 10]; //str = 1 //产生了一个新对象,原对象的计数器不变 NSMutableString *str = [string mutableCopy]; NSLog(@"str:%zi",[string retainCount]); NSLog(@"string:%zi",[str retainCount]); //修改副本,原对象不变 [str appendString:@"abcd"]; NSLog(@"string:%@",string); NSLog(@"str:%@",str); //string =0 [string release]; [str release];//copy也需要release } //不可变拷不可变--浅拷贝 //浅拷贝--指针拷贝--地址拷贝 (拷贝指针,不会产生新的对象,返回原对象本身,原对象计数器+1) void stringcopy(){ NSString *string = [[NSString alloc]initWithFormat:@"age is %i", 10]; //为了性能着想,针对copy原则,string本来是不可变,[string copy]并没有产生一个新的对象,而是返回对象本身,copy相当与retain NSString *str = [string copy];//产生一个不可变对象 //NSLog(@"%i", string == str);//结果为1,copy出来的对象为同一个 NSLog(@"%zi",[string retainCount]); NSLog(@"%zi",[str retainCount]); [string release]; [str release];//使用copy或者mutablecopy都需要release } #pragma mark 可变字符串的copy //深拷贝 void mutableStringCopy(){ NSMutableString *string = [NSMutableString stringWithFormat:@"age is %i",10]; NSString *str = [string copy];//产生一个不可变的str [str release]; } //深拷贝 void mutableStringmutableCopy(){ NSMutableString *string = [NSMutableString stringWithFormat:@"age is %i",10]; //会产生一个新的对象 NSMutableString *str = [string mutableCopy]; [str appendString:@"1234"]; NSLog(@"str:%@",str); NSLog(@"string%@",string); [str release]; }
时间: 2024-11-05 03:26:55