標籤:
#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]; }
Objective-C文法之copy和mutablecopy