2011-03-09 63 views
0

我對Objective-C的新世界很陌生,所以我有幾個關於集體成員聲明的問題。請注意在下面的代碼中的註釋:關於集體成員聲明的問題

在頭文件中我有代碼,

@interface MyClass : NSObject { 

    //what we points here ? Object or something else ? 
    NSString *myString; 
    } 
    // In interface we declare NSTring *myString in @property declaration is (NSString *) myString. 
    // What is the difference here ? Why we don`t use the same declaration as above ? 
    @property(nonatomic, retain) (NSString *) myString; 
    @end 

回答

1

你缺少的是實例變量(在花括號之間定義)不能從外部訪問(即其他對象)。要做到這一點 - 您必須爲實例var定義屬性(通過使用關鍵字@property)來了解外部對象如何訪問給定實例var的值。同樣在實現文件(.m)中,您必須爲其適當的屬性提供@synthesize實例變量訪問器方法。請注意,@property聲明不僅定義了它所持有的內容(NSString *myString),還包含它如何被訪問和設置。您可以將屬性定義爲只讀(@property (readonly)...)或一次只能從幾個線程訪問(@property (nonatomic))。

而且 - 如果您的實例變量被從它代表的其他對象的屬性不同的名稱 - 你必須表明,在實現文件(@synthesize propertyName=instanveVariableName

更新

MyClass *myInstance = [[MyClass alloc] init]; 
[myInstance myString]; // returns myString property 

嘗試了上述2運行沒有@property的代碼行,你會看到不同之處。

+0

爲什麼我們寫: @property(非原子,保留)(的NSString * )myString,而不是 @property(nonatomic,retain)NSString * myString; ? – prista 2011-03-09 11:10:45

+0

因此可以從外部對象訪問它。 – Eimantas 2011-03-09 11:12:12

0

其實你正在定義亞爾類的屬性。

@interface MyClass : NSObject { 
//public object 
@public 
NSString *myString; 
//private object 
NSString *myString2; 
    }

0

的OBJ-C

.h文件中

@interface MyClass : NSObject { 

     //Your member variable; 
     // you member objects; 
    } 

//property declarations 

//function declarations 

@end 

類結構,因此它應該看起來像

@interface MyClass : NSObject { 

     NSString *str; 
    } 
@property(nanatomic,retain) NSString *str; 

-(void)method; 

@end