簡體   English   中英

objective-c ARC只讀屬性和私有setter實現

[英]objective-c ARC readonly properties and private setter implementation

在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,則不能再使用retain / release關鍵字,這是否足夠正確?

// interface declaration:
@property (nonatomic, strong, readonly) NSString *myProperty;

// Setter override
- (void)setMyProperty:(NSString *)newValue
{ 
   if (myProperty != newValue) {
      myProperty = newValue;
   }
}

是的,這是足夠的,但你甚至不需要那么多。

你可以做

- (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

這樣做,你只需要合成,你就有了一個為你合成的私人設定器。

您可以在接口擴展中將您的屬性重新聲明為readwrite

@interface SomeClass()
@property (nonatomic, strong, readwrite) NSString *myProperty;
@end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM