复制自定义类对象[重复]

问题描述 投票:0回答:3

我有一个自定义类,它有一些属性。我想复制这个类的一个对象,这样我就得到了具有相同内容的第二个对象。
示例:

MyCustomClass *objectName = [[MyCustomClass alloc] init];
// fill here with some properties
objectName.propertyOne = @"smth";
objectName.propertyTwo = @"smth";
// And copy my object
MyCustomClass *secontObject = [objectName copy];

是否存在类似“复制”的方法?

注意:已经内置的真实复制方法没有帮助。

ios objective-c cocoa cocoa-touch copy
3个回答
2
投票

没有内置任何内容。为此包含了 NSCopying 协议,但由于它只是一个协议,因此您必须自己实现复制逻辑。


2
投票

要使用 copy 方法,您首先需要为自定义类实现 NSCopying 协议:

@interface SomeClass : NSObject <NSCopying> 

@property (nonatomic, strong) NSString *string;
@property (nonatomic, strong) NSNumber *number;

@end


@implementation SomeClass

- (id)copyWithZone:(NSZone*)zone
{
     SomeClass *copyObject = [SomeClass new];
     copyObject.string = _string;
     copyObject.number = _number;

     return copyObject;
}

. . . . . . .

@end

1
投票

您无法复制自定义类。 您需要自己实现复制逻辑。

参见 如何在目标 c 中复制对象

© www.soinside.com 2019 - 2024. All rights reserved.