Objective-c ARC readonly свойства и реализация private setter
До ARC, если бы я хотел, чтобы свойство было только для чтения, но его можно было записать в класс, я мог бы сделать:
// Public declaration
@interface SomeClass : NSObject
@property (nonatomic, retain, readonly) NSString *myProperty;
@end
// private interface declaration
@interface SomeClass()
- (void)setMyProperty:(NSString *)newValue;
@end
@implementation SomeClass
- (void)setMyProperty:(NSString *)newValue
{
if (myProperty != newValue) {
[myProperty release];
myProperty = [newValue retain];
}
}
- (void)doSomethingPrivate
{
[self setMyProperty:@"some value that only this class can set"];
}
@end
С ARC, если бы я хотел переопределить setMyProperty, вы больше не можете использовать слова сохранения/выпуска, так это правильно и правильно?
// interface declaration:
@property (nonatomic, strong, readonly) NSString *myProperty;
// Setter override
- (void)setMyProperty:(NSString *)newValue
{
if (myProperty != newValue) {
myProperty = newValue;
}
}
Ответы
Ответ 1
Да, это адекватно, но вам даже этого не нужно.
Вы можете сделать
- (void)setMyProperty:(NSString *)newValue
{
myProperty = newValue;
}
Компилятор сделает все правильно.
Иная вещь, хотя, вам даже не нужна ЭТО. В расширении вашего класса вы можете фактически отражать объявления @property
.
@interface SomeClass : NSObject
@property (nonatomic, readonly, strong) NSString *myProperty;
@end
@interface SomeClass()
@property (nonatomic, readwrite, strong) NSString *myProperty;
@end
Выполняя это, вам просто нужно синтезировать, и у вас есть собственный сеттер, который синтезирован для вас.
Ответ 2
Вы можете повторно использовать свое свойство как readwrite
в расширении интерфейса:
@interface SomeClass()
@property (nonatomic, strong, readwrite) NSString *myProperty;
@end