仅合成setter以声明可变类

时间:2014-07-01 10:18:01

标签: ios iphone objective-c cocoa

我正在尝试创建Mutable和Immutable类。

有Person协议,Person类和MutablePerson类。

我想创建名称属性,并仅合成getter MutablePerson类的Person类和setter。我怎么能这样做?

@protocol Person <NSObject>

@property (nonatomic, readonly, copy) NSString *name;

@end

@interface Person : NSObject <Person>

@end

@interface MutablePerson : Person

@property (nonatomic, copy) NSString *name;

@end

当我尝试在MutablePerson类中合成setter时出错。 我怎样才能合成属性的setter?

1 个答案:

答案 0 :(得分:1)

根据您的示例,我不确定您在使用继承创建MutablePerson时使用协议来确定您的Person名称。

我只使用继承设置了一个基本的Person和MutablePerson对象,它似乎工作正常:

Person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject 

@property (nonatomic, strong, readonly) NSString *name;

- (id)initWithName:(NSString*)name;

@end

@interface MutablePerson : Person

@property (nonatomic, strong, readwrite) NSString *name;

@end

Person.m

#import "Person.h"

@interface Person ()

@property (nonatomic, strong, readwrite) NSString *name;

@end

@implementation Person

- (id)initWithName:(NSString *)name {
    if (self = [super init]) {
        _name = name;
    }
    return self;
}

@end

@implementation MutablePerson

@end

如果这不是您想要的行为,请告诉我,如果可以的话,我会编辑我的回复以帮助您。

编辑:这是我用来创建示例Person和MutablePerson的示例代码:

    Person *testPerson = [[Person alloc] initWithName:@"TestName"];

    MutablePerson *testMutablePerson = [[MutablePerson alloc] init];
    testMutablePerson.name = @"MutableName";