NSMutablecopy NSCopy
2015-11-02 19:16 1314256 阅读(204) 评论(0) 编辑 收藏 举报拷贝只是增加了一个指针指向已经存在的内存,而深拷贝就是增加一个指针并且申请一个新的内存,使这个增加的指针指向这个新的内存
//拷贝分为深拷贝和浅拷贝 浅拷贝:不产生新的对象,直接指向原有对象
//深拷贝:产生新的对象,其内容是原有对象的内容
//拷贝:NSCopy、NSMutableCopy
//NSCopy拷贝出的结果是不可变对象,跟其接受类型没有关系,跟其传入类型也没有关系,NSMutablecopy拷贝的结果是可变对象,跟其传入的类型没有关系,但是会受其接收类型的影响,
//当使用NSCopy复制一个不可变对象时,其行为是浅复制,其余情况都是深拷贝
//当使用NSMutablecopy时,是深拷贝
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
/* NSCopy
NSString *str = [NSString stringWithFormat:@"123"];
(接受类型) (传入类型)
|| ||
NSString *str1 = [str copy]; //浅拷贝,地址不变,跟其接受类型没有关系,跟其传入类型也没有关系
NSMutableString *str2 = [str copy];
NSMutableString *str3 = [NSMutableString stringWithFormat:@"222"];
NSString *str4 = [str3 copy];
NSLog(@"%p,%p",str1,str); //深拷贝,产生新地址
跟其传入的类型没有关系,但是会受其接收类型的影响,
*/
/* NSMutableCopy*/
NSString *str = [NSString stringWithFormat:@"123"];
NSMutableString *s = [str mutableCopy];
[s setString:@"23"];
NSLog(@"%p,%p",s,str);
}
return 0;
}
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *p = [[Person alloc] init];
NSMutableString *s = [NSMutableString stringWithFormat:@"汉三"];
p.name = s;
// p.name = @"aaa";
NSMutableString *s = [NSMutableString stringWithFormat:@"汉三"];
p.name = s;
// p.name = @"aaa";
NSLog(@"%@",p);
Person *p1 = [p mutableCopy];
[s setString:@"王五"];
p1.name = s;
NSLog(@"%@,%@",p,p1);
}
return 0;
p1.name = s;
NSLog(@"%@,%@",p,p1);
}
return 0;
}
//如果自定义类想要实现拷贝操作,首先需要遵循NSCopying和NSMutableCopying协议,
#import <Foundation/Foundation.h>
@interface Person : NSObject<NSCopying,NSMutableCopying>
@property (nonatomic, copy) NSString *name;
#import <Foundation/Foundation.h>
@interface Person : NSObject<NSCopying,NSMutableCopying>
@property (nonatomic, copy) NSString *name;
@end
#import "Person.h"
@implementation Person
-(NSString *)description{
return _name;
}
//如果直接return self,则是浅拷贝,如果使用alloc,则是深拷贝
-(id)copyWithZone:(NSZone *)zone{
Person *p = [Person allocWithZone:zone];
@implementation Person
-(NSString *)description{
return _name;
}
//如果直接return self,则是浅拷贝,如果使用alloc,则是深拷贝
-(id)copyWithZone:(NSZone *)zone{
Person *p = [Person allocWithZone:zone];
// p.name = [self.name copy];
return p;
}
//如果直接return self,则是浅拷贝,如果使用alloc,则是深拷贝
-(id)mutableCopyWithZone:(NSZone *)zone{
Person *p = [Person allocWithZone:zone];
// p.name = [self.name copy];
return p;
}
//如果直接return self,则是浅拷贝,如果使用alloc,则是深拷贝
-(id)mutableCopyWithZone:(NSZone *)zone{
Person *p = [Person allocWithZone:zone];
// p.name = [self.name copy];
return p;
}
@end