我有一个名为 SuperClass 的父类(super class),它是一个只读属性。看起来像这样:
@property (nonatomic, strong, readonly) NSArray *arrayProperty;
在一个子类中,我需要一个将 SuperClass 的实例作为参数的初始化器:
- (instancetype)initWithSuperClass:(SuperClass *)superClass
我创建了一个显示问题所在的 GitHub 示例项目:https://github.com/marosoaie/Objc-test-project
我不能在初始化程序中执行 _arrayProperty = superClass.arrayProperty
。
我也想在 SubClass 中将属性保持为只读。
关于如何解决这个问题有什么想法吗?
我知道我可以在 SubClass 实现文件中的类扩展中将该属性声明为读写,但我希望有比这更好的解决方案。
编辑: 父类(super class).h
#import <Foundation/Foundation.h>
@interface SuperClass : NSObject
- (instancetype)initWithDictionary:(NSDictionary *)dictionary;
@property (nonatomic, strong, readonly) NSString *stringProperty;
@property (nonatomic, strong, readonly) NSArray *arrayProperty;
@end
父类(super class).m
#import "SuperClass.h"
@implementation SuperClass
- (instancetype)initWithDictionary:(NSDictionary *)dictionary
{
self = [super init];
if (self) {
_arrayProperty = dictionary[@"array"];
_stringProperty = dictionary[@"string"];
}
return self;
}
@end
子类.h:
#import <Foundation/Foundation.h>
#import "SuperClass.h"
@interface SubClass : SuperClass
@property (nonatomic, strong, readonly) NSString *additionalStringProperty;
- (instancetype)initWithSuperClass:(SuperClass *)superClass;
@end
子类.m:
#import "SubClass.h"
@implementation SubClass
@synthesize additionalStringProperty = _additionalStringProperty;
- (NSString *)additionalStringProperty
{
if (!_additionalStringProperty) {
NSMutableString *mutableString = [[NSMutableString alloc] init];
for (NSString *string in self.arrayProperty) {
[mutableString appendString:string];
}
_additionalStringProperty = [mutableString copy];
}
return _additionalStringProperty;
}
- (instancetype)initWithSuperClass:(SuperClass *)superClass
{
self = [super init];
if (self) {
// Doesn't work
// _stringProperty = superClass.stringProperty;
// _arrayProperty = superClass.arrayProperty;
}
return self;
}
@end
最佳答案
您已经公开了一个初始化器,它写入只读属性 -initWithDictionary:
。在您的子类中调用它,而不是 [super init]
:
- (instancetype)initWithSuperClass:(SuperClass *)superClass {
NSDictionary *dict = @{
@"array": superClass.arrayProperty,
@"string": superClass.stringProperty,
};
self = [super initWithDictionary:dict];
if (self) {
// Nothing here.
}
return self;
}
为只读属性设置初始化器是很常见的,尽管使用字典并不是很好的解决方案。通常,我会创建:
- (instancetype)initWithArray:(NSArray *)array string:(NSString *)string;
关于ios - 子类中的 Objective-C 只读属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27578493/