我有一个自定义类,它有一些属性。我想复制这个类的一个对象,这样我就得到了具有相同内容的第二个对象。
示例:
MyCustomClass *objectName = [[MyCustomClass alloc] init];
// fill here with some properties
objectName.propertyOne = @"smth";
objectName.propertyTwo = @"smth";
// And copy my object
MyCustomClass *secontObject = [objectName copy];
是否存在类似“复制”的方法?
注意:已经内置的真实复制方法没有帮助。
没有内置任何内容。为此包含了 NSCopying 协议,但由于它只是一个协议,因此您必须自己实现复制逻辑。
要使用 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
您无法复制自定义类。 您需要自己实现复制逻辑。