2

我有以下课程。

@interface classB : classA

@property NSString* token;


@end

@interface classA 

@property NSString* name;
@property float email;

@end

我基本上想创建一个classB的实例,其继承的(classA)是classA的另一个实例的副本。无需为每个属性手动复制。

我试过 copyWithZone 但我认为这不是正确的道路。

4

1 回答 1

1

我不相信有办法自动神奇地做到这一点。但是,基于对这个问题的回答(自动复制属性值...),我想出了一个可以使用的相当简单的方法。

首先,假设您的类继承自 NSObject,使用以下方法向 NSObject 添加一个类别(或者,您可以将此方法添加到 A 类):

#import <objc/runtime.h>

- (NSSet *)propertyNames
{
    NSMutableSet *propNames = [NSMutableSet set];
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        [propNames addObject:propertyName];
    }
    free(properties);

    return propNames;
}

这将为您提供NSSet *所有属性名称作为NSStrings。

然后,对于 B 类,创建以下方法,将 A 类作为输入,初始化 B 类的一个实例,遍历 A 类的属性名称,并将它们复制到 B 类。

- (id)initWithClassA:(ClassA *)classA
{
    self = [super init];

    if(self)
    {
        NSSet *propertyNames = [classA propertyNames];

        for(NSString *propertyKey in propertyNames)
        {
            id value = [classA valueForKey:propertyKey];
            [self setValue:[value copy] forKey:propertyKey];
        }
    }

    return self;
}
于 2013-08-02T19:27:37.687 回答