ios copy关键字的使用
来源:互联网 发布:泰国 知乎 编辑:程序博客网 时间:2024/05/16 11:20
转自:http://jordy.easymorse.com/?cat=26
copy关键字的使用
平时我们使用对象之间的传值都是采用retain count +1的方式,这种方式的适用于当对象的某属性的值改变时,引用该对象的不同指针会同时改变,因为这两个指针指向的是同一个内存地址,
但如果需求是,当一个指针执行的对象属性值发生改变时,不影响另一个对象,那么需要分配两个不同的内存地址,也就是说,我们就不可以采用retain关键字了,而是要采用copy 关键字,因为copy关键字会在复制时重新创建一个新的对象。 举例说明一下copy使用
这里创建一个Person类
Person.h,代码:
@interface Person : NSObject <NSCopying>{
NSString *name;
NSString *email;
}
@property (nonatomic, retain) NSString *name;
@property (nonatomic,retain)NSString *email;
@end
Person.m文件
#import “Person.h”
@synthesize name,email;
- (id)initWithName:(NSString *)theName andEmail:(NSString *)theEmail
{
self = [super init];
if (self){
self.name = theName;
self.email = theEmail;
}
}
- (id)copyWithZone:(NSZone *)zone
{
Person *aPerson = [[Person allocWithZone:zone] initWithName:[self name] andEmail:[self email]];
return aPerson;
}
- (void)delloc
{
[name release];
[email release];
[super dealloc];
}
这里说明一下,
在对象之间copy,首先需要类是继承自NSObject,其次需要实现<NSCoding>协议,最后在方法中实现
- (id)copyWithZone:(NSZone *)zone 方法
如果没有此方法那么在copy对象,程序会直接宕机,并提示Person类找不到copyWithZone方法。
这里还有一点需要注意的是,通常在NSArray之间copy,是retain方式的复制,也就是直接将引用系数+1,
如下 代码:
NSArray *array1 = [[NSArray alloc] initWithObjects:person1,person2,person3,nil];
NSMutableArray *array2 = [array1 copy]; 或使用
NSMutableArray *array2 =[ [NSMutableArray alloc] initWithArray:array1];
如果想使用两个不同内存,那么就需要使用到NSArray 的deep copy,例如:
NSArray *array1 = [[NSArray alloc] initWithObjects:person1,person2,person3,nil];
NSMutableArray *array2 = [[NSMutableArray alloc] initWithArray:array1 copyItems:YES];
- ios copy关键字的使用
- ios copy关键字的使用
- ios copy关键字的使用
- ios copy关键字的使用
- iOS Copy 关键字 的使用 原创 + 转载
- copy关键字的使用
- iOS开发怎么使用copy关键字
- iOS的copy,strong,weak,assign关键字的使用,网罗下来大概总结一下
- IOS-36-Object-C语法之属性关键字的使用(assign/weak/strong/copy)
- iOS常用关键字(assign, copy,retain等)的使用与区别
- iOS 关键字 copy,assign,strong,retain,weak,readonly,readwrite,nonatomic,atomic,unsafe_unretained的使用与区别
- ios之关键字retain / copy / mutableCopy 使用技巧
- NSString 使用 copy 关键字和 strong 关键字修饰的异同
- iOS中assign、copy 、retain等关键字的含义
- iOS中assign、copy 、retain等关键字的含义
- iOS中assign、copy 、retain等关键字的含义
- iOS中assign、copy 、retain等关键字的含义
- iOS中assign、copy 、retain等关键字的含义
- 记录1
- linux系统加固
- ARM裸机调试资料1
- ASP.NET MVC案例教程(基于ASP.NET MVC beta)——第五篇:MVC整合Ajax
- JAVA泛型总结
- ios copy关键字的使用
- 设计模式
- 智能指针
- 读CopyOnWriteArrayList有感
- ACE的ACE_Logging_Strategy类中的一个多线程安全问题的发现及解决过程
- ASP.NET MVC案例教程(基于ASP.NET MVC beta)——第六篇:拦截器
- S3C2440中断解析和基于WINCE操作系统的中断分析(整理于网络,用于按键中断使用)
- WebKit的智能指针分析 - Part 1:RefCounted
- ASP.NET MVC案例教程(基于ASP.NET MVC beta)——第七篇:闲话ASP.NET MVC