ben*_*ben 110 copy objective-c
我需要深度复制具有自己的对象的自定义对象.我一直在阅读,并对如何继承NSCopying以及如何使用NSCopyObject感到困惑.有人可以帮帮我吗?谢谢阅读!
Ada*_*ght 189
与引用类型一样,有两种"复制"概念.我相信你知道他们,但是为了完整.
你想要后者.如果这是您自己的对象之一,则只需采用协议NSCopying并实现 - (id)copyWithZone:(NSZone*)区域.你可以自由地做任何你想做的事情; 虽然这个想法是你自己制作一个真实的副本并将其归还.您可以在所有字段上调用copyWithZone,以进行深层复制.一个简单的例子是
@interface YourClass : NSObject <NSCopying>
{
SomeOtherObject *obj;
}
// In the implementation
-(id)copyWithZone:(NSZone *)zone
{
// We'll ignore the zone for now
YourClass *another = [[YourClass alloc] init];
another.obj = [obj copyWithZone: zone];
return another;
}
Run Code Online (Sandbox Code Playgroud)
Saq*_*aud 23
Apple文档说
copyWithZone:方法的子类版本应该首先将消息发送到super,以合并其实现,除非子类直接从NSObject下降.
添加到现有答案
@interface YourClass : NSObject <NSCopying>
{
SomeOtherObject *obj;
}
// In the implementation
-(id)copyWithZone:(NSZone *)zone
{
YourClass *another = [super copyWithZone:zone];
another.obj = [obj copyWithZone: zone];
return another;
}
Run Code Online (Sandbox Code Playgroud)
Fel*_*rós 21
我不知道该代码和我的代码之间的区别,但我对该解决方案有问题,所以我再读一点,发现我们必须在返回之前设置对象.我的意思是:
#import <Foundation/Foundation.h>
@interface YourObject : NSObject <NSCopying>
@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *line;
@property (strong, nonatomic) NSMutableString *tags;
@property (strong, nonatomic) NSString *htmlSource;
@property (strong, nonatomic) NSMutableString *obj;
-(id) copyWithZone: (NSZone *) zone;
@end
@implementation YourObject
-(id) copyWithZone: (NSZone *) zone
{
YourObject *copy = [[YourObject allocWithZone: zone] init];
[copy setNombre: self.name];
[copy setLinea: self.line];
[copy setTags: self.tags];
[copy setHtmlSource: self.htmlSource];
return copy;
}
Run Code Online (Sandbox Code Playgroud)
我添加了这个答案,因为我在这个问题上遇到了很多问题,我不知道为什么会这样.我不知道区别,但它对我有用,也许对其他人也有用:)
归档时间: |
|
查看次数: |
110353 次 |
最近记录: |