1、NSString NSMutableString NSDictionary NSMutableDictionary NSArray NSMutableArray 使用copy和mutableCopy方法
/**
1、拷贝的作用
新指针和旧指针指向的对象内容要一样
修改旧的对象不会改变新的对象
2、拷贝类型
深拷贝:内容拷贝,会产生新的对象,不同的对象,内容相同
浅拷贝:指针拷贝,不会产生新的对象,指向的是同一个对象
*/
#import <Foundation/Foundation.h>
#pragma String类型调用mutableCopy方法
void stringMutableCopy1(){
NSString *new = [[NSString alloc] initWithFormat:@"Hello world"];
NSMutableString * mutableString = [new mutableCopy];
[mutableString appendString:@"Jack"];
NSLog(@"new -- %@",new);
NSLog(@"mutableString -- %@",mutableString);
}
#pragma String类调用copy方法的时候,产生新的String对象,如果使用string对象调用相关的方法,这个对象本身不会改变,返回的数据会发生改变
void stringCopy(){
NSString *old = [[NSString alloc]initWithFormat:@"Java"];
NSString *new = [old copy];
NSString *third = [new stringByAppendingString:@"world"];
NSLog(@"old ---%@",old);
NSLog(@"new ---%@",new);
NSLog(@"third -- %@",third);
}
void mutableStringCopy(){
NSMutableString * old = [[NSMutableString alloc]initWithFormat:@"Jake"];
NSString * new = [old copy];
[new stringByAppendingString:@" ios is good"];
NSLog(@"old %@",old);
NSLog(@"new %@",new);
}
void mutableStringMutableCopy(){
NSMutableString * old = [[NSMutableString alloc]initWithFormat:@"Jake"];
NSMutableString * new = [old mutableCopy];
[new appendString:@" ios is good"];
NSLog(@"old %@",old);
NSLog(@"new %@",new);
}
void directoryCopy(){
// NSNumber * number = [NSNumber numberWithInt:15];
NSDictionary * oldDictionary = @{@"name":@"zhangsan",@"age":[NSNumber numberWithInt:15] };
NSDictionary * newDictionary = [oldDictionary copy];
NSLog(@"oldDictionary--%@",oldDictionary);
NSLog(@"newDictionary--%@",newDictionary);
}
void dictionaryMutcopy(){
NSMutableDictionary * oldMutableDictionary = [NSMutableDictionary dictionary];
[oldMutableDictionary setObject:@"zhangfeifei" forKey:@"name"];
[oldMutableDictionary setObject:@25 forKey:@"age"];
NSMutableDictionary * newMutableDictionary = [oldMutableDictionary mutableCopy];
[newMutableDictionary setObject:@190 forKey:@"weight"];
NSLog(@"oldMutableDictionary---%@",oldMutableDictionary);
NSLog(@"newMutableDictionary---%@",newMutableDictionary);
}
void arrayMutableCopy(){
NSMutableArray * mutableArray = [[NSMutableArray alloc]init];
[mutableArray addObject:@12];
[mutableArray addObject:@12];
NSMutableArray * newMutableArray = [mutableArray mutableCopy];
[newMutableArray addObject:@17];
NSLog(@"mutableArray %@",mutableArray);
NSLog(@"newMutableArray %@",newMutableArray);
}
int main(int argc, const char * argv[])
{
@autoreleasepool {
stringMutableCopy1();
stringCopy();
mutableStringCopy();
directoryCopy();
dictionaryMutcopy();
arrayMutableCopy();
}
return 0;
}