1、Objective-C 分深浅复制,可变和不可变复制
// // main.m // sample004 // // Created by echoliu on 13-1-24. // Copyright (c) 2013年 echoliu. All rights reserved. // #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... // 复制 非容器对象 对象本身不可变 NSString *str=@"Origin string ";//定义一个常用字符串 NSString *strcopy=[str copy]; NSLog(@" str is %@",str); NSLog(@" str copy is %@",strcopy); NSMutableString *strmcopy=[str mutableCopy]; NSLog(@" str copy is %@",strmcopy); [strmcopy appendFormat:@" this is copy mutable"]; NSLog(@" str copy is %@",strmcopy); //复制 非容器对象 对象本身可变 NSMutableString * mstr=[NSMutableString stringWithString:@"origin"]; NSString * mstrcopy=[mstr copy]; NSMutableString *mstrmcopy=[mstr copy];//这里很奇怪,居然是不可变副本 NSLog(@" str copy is %@",mstrcopy); NSLog(@" str copy is %@",mstrmcopy); //[mstrmcopy appendFormat:@"abc"]; NSMutableString *mstrmcopy2=[mstr mutableCopy]; [mstrmcopy2 appendFormat:@" abc"]; NSLog(@" str copy is %@",mstrmcopy2); NSArray * array1=[NSArray arrayWithObjects:@"s",@"f",@"f", nil]; NSArray * array1copy=[array1 copy]; for(NSString * ms in array1){ NSLog(@"%@",ms); } for(NSString * ms in array1copy){ NSLog(@"%@",ms); } //mutable NSMutableArray *marraycopy=[array1 mutableCopy]; [marraycopy addObject:@" addobj"]; for(NSString * ms in marraycopy){ NSLog(@"%@",ms); } [marraycopy removeObjectAtIndex:0];//删除第一个元素 for(NSString * ms in marraycopy){ NSLog(@"%@",ms); } [marraycopy removeLastObject];//删除最后一个元素 for(NSString * ms in marraycopy){ NSLog(@"%@",ms); } [marraycopy removeAllObjects]; [marraycopy removeLastObject];//删除最后一个元素 for(NSString * ms in marraycopy){ NSLog(@"%@",ms); } //定义一个内容可变的容器 NSArray *marray1=[NSArray arrayWithObjects:[NSMutableString stringWithString: @"a"],@"b",@"c", nil]; for(NSString * ms in marray1){ NSLog(@"%@",ms); } //不可变复制 NSArray *marray1copy=[marraycopy copy]; //可变复制 NSMutableArray *marraymcopy1=[marray1 mutableCopy]; for(NSString * ms in marraymcopy1){ NSLog(@"%@",ms); } //获取一个字符串 NSMutableString *tstr=[marray1 objectAtIndex:0]; NSLog(@"string copy is %@",tstr); tstr=@"other value"; NSLog(@"string copy is %@",tstr); [tstr appendString:@"ok last add"]; } return 0; }
类的复制 <NSCopying>协议实现,实现类的复制需要实现对该接口的实现,且需要在实现文件m中增加重写方法
如下:
头文件
// // samplecopy.h // sample004 // // Created by echoliu on 13-1-25. // Copyright (c) 2013年 echoliu. All rights reserved. // #import <Foundation/Foundation.h> //NSCopying 协议 @interface samplecopy : NSObject<NSCopying> -(void)print; @end
实现文件
// // samplecopy.m // sample004 // // Created by echoliu on 13-1-25. // Copyright (c) 2013年 echoliu. All rights reserved. // #import "samplecopy.h" @implementation samplecopy -(id)copyWithZone:(NSZone *)zone{ return self; } -(void)print{ NSLog(@"this is copy class"); } @end