如何实现将自定义对象作为参数传递的initWith方法?

时间:2013-05-31 16:58:49

标签: objective-c class initialization runtime

例如,我有以下课程:

@interface PrivateInfo: NSObject

- (instancetype)initWithPrivateInfoObject:(PrivateInfo *)pi;

@end

@implementation PrivateInfo
{
   @private
   NSString *name;
   NSString *creditCardID;
}

- (instancetype)initWithPrivateInfoObject:(PrivateInfo *)pi
{
   // how to init current object with passed pi ?
}

- (PrivateInfo *)copy
{
  // how to create a copy of current object?
}
@end

1 个答案:

答案 0 :(得分:2)

假设ARC:

·H:

@interface PrivateInfo: NSObject <NSCopying>

- (instancetype)initWithPrivateInfoObject:(PrivateInfo *)pi;

@end

的.m:

@implementation PrivateInfo {
    NSString *name;
    NSString *creditCardID;
}

- (instancetype)initWithPrivateInfoObject:(PrivateInfo *)pi
{
    self = [super init];
    if (self) {
        name = pi->name;
        creditCardID = pi->creditCardID;
    }

    return self;
}

- (PrivateInfo *)copyWithZone:(NSZone *)zone {
    PrivateInfo *res = [[PrivateInfo alloc] initWithPrivateInfoObject:self];

    return res;
}

@end

@private块中不需要@implementation来声明ivars。并且要使用NSCopying协议来复制对象。