I have a superclass called SuperClass a read-only property. That looks like this:
@property (nonatomic, strong, readonly) NSArray *arrayProperty;
In a subclass I need an initializer that takes a instance of SuperClass as a parameter:
- (instancetype)initWithSuperClass:(SuperClass *)superClass
I created a GitHub sample project that shows what the problem is: https://github.com/marosoaie/Objc-test-project
I cannot do _arrayProperty = superClass.arrayProperty
in the initializer.
I want to keep the property read-only in SubClass as well.
Any ideas on how this could be solved?
I know I could declare the property as readwrite in a class extension inside the SubClass implementation file, but I'm hoping that there's a better solutions than this.
Edit: SuperClass.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
SuperClass.m
#import "SuperClass.h"
@implementation SuperClass
- (instancetype)initWithDictionary:(NSDictionary *)dictionary
{
self = [super init];
if (self) {
_arrayProperty = dictionary[@"array"];
_stringProperty = dictionary[@"string"];
}
return self;
}
@end
SubClass.h:
#import <Foundation/Foundation.h>
#import "SuperClass.h"
@interface SubClass : SuperClass
@property (nonatomic, strong, readonly) NSString *additionalStringProperty;
- (instancetype)initWithSuperClass:(SuperClass *)superClass;
@end
SubClass.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