2011-03-09 67 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