簡體   English   中英

Objective C中的屬性(自我讀寫,其他讀取)

[英]Properties in Objective C (readwrite for self and readonly for others)

在iOS應用程序中,我需要一個屬性,該屬性對於其他類只讀,但是為自己調用readwrite 所以我按照這個問題編寫了我的代碼,

在.h:

@interface TheClassName : NSObject {
     NSString* str;
}
@property(nonatomic, retain, readonly) NSString* str;
@end

在.m:

@interface TheClassName()
@property(nonatomic, retain, readwrite) NSString* str;
@end

@implementation TheClassName
-(id)init {
     if(self = [super init]) {
          str = [[NSString alloc] initWithString:@"hello"];
     }
     return self;
}
@end

根據Apple文檔,此過程也有效。 但我試着嘗試我的代碼,問題就開始了。

我所做的一切被忽略相對於舍瓦阿列克謝耶夫的答案.m文件@interface部分在這里 ,但是編譯器沒有顯示警告或錯誤,當我用它作為str = [[NSString alloc] initWithString:@"hello"].m文件中 !!

我的意思是,該屬性設置為readonly ,因此該語句應該產生錯誤,但它沒有。 為什么??

注意:我使用的是Xcode 5.1.1

這段代碼:

str = [[NSString alloc] initWithString:@"hello"];

不調用屬性setter,它引用您直接定義的實例變量:

@interface TheClassName : NSObject {
     NSString* str;
}

並且,默認情況下,后備實例變量將被稱為_str ,因此您應該刪除該實例變量定義並直接引用_str (如果您不想創建該屬性的readwrite版本)。 當前標准的物業str將不參考實例變量str沒有明確使用@synthesize str = str; 聲明。

暫無
暫無

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

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