开发者

Why should we declare variables for @property

I am n开发者_JAVA技巧ewbie in Objective. As I read many tutorial, @property has a variable for a type, the same variable is declared in @inferface too. Is this needed?

Example

@interface MyInterface : NSObject
{
   NSInteger myVaribale;
}
@property(retain) NSInteger myVariable; 

Here myVariable is declared in both place.


since iOS 4, you can write

@interface MyInterface : NSObject {
}

@property(assign) NSInteger myVariable; 

@implementation MyInterface
@synthesize myVariable;
@end

Meaning you can omit the NSInteger myVaribale in your interface declaration as long as you synthesize it in the .m (the synthesize will create setter, getter and instance variable)

A drawback is that you won't see the value of myVariable in Xcode's debugger.


As a note, the redeclaration of the ivar's type in the @property statement can also be useful if you want to declare the property as the immutable type of the ivar's, for instance:

@interface MyClass : NSObject
{
    NSMutableArray *myArray;
}

@property (retain) NSArray *myArray;

In this instance, the ivar is actually stored as an NSMutableArray, so it can be altered during the object's lifecycle.

However this is an internal detail and if you don't want to "advertise" is as being mutable (changeable), you can make the type of the property the immutable type – in this case an NSArray.

Although this won't actually stop other code using the returned array as mutable, it is good convention and notifies other code that it shouldn't treat it in this way.


It's not an inconvenience but more a basic concept of objc: A class can have member variables. In OOP you normally define getter and setters for member variables which should be available to the outside. In objective-c you are encouraged to define getters/setters at any time (if they should be private, put their declarations into a private interface). To simplify this task, objective-c uses properties which are not more than a abbreviation. Additionally there are things like key-value-coding and -observing which are enabled by properties, but basically, they are just abbreviations for getters and setters.

Conclusion: Inside of @interface you declare members, outside methods including getters/setters (properties).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜