Why should we declare variables for @property

I am new to Objective. When I read a lot of lessons, @property has a variable for the type, the same variable is also declared in @inferface. It's necessary?

Example

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

Here myVariable is declared in both cases.

+1
source share
3 answers

since iOS 4 you can write

 @interface MyInterface : NSObject { } @property(assign) NSInteger myVariable; @implementation MyInterface @synthesize myVariable; @end 

You can omit the value of NSInteger myVaribale in the interface declaration until you synthesize it in .m (the synthesis will create the variable setter, getter and instance)

The downside is that you won't see the myVariable value in the Xcode debugger.

+6
source

As a side note, overriding the ivar type in the @property statement @property also be useful if you want to declare a property as a type immutable for ivar, for example:

 @interface MyClass : NSObject { NSMutableArray *myArray; } @property (retain) NSArray *myArray; 

In this case, ivar is actually stored as NSMutableArray , so it can be changed during the life cycle of the object.

However, this is an internal detail, and if you do not want to β€œadvertise” as mutable (mutable), you can make the property type an immutable type β€” in this case, NSArray .

Although this will not actually stop the other code using the returned array as mutable, this is a good convention and notifies the other code that it should not be treated like that.

+5
source

This is not an inconvenience, but the more basic concept of objc: a class can have member variables. In OOP, you usually define getters and setters for member variables that should be accessible externally. In objective-c, you are advised to define getters / setters at any time (if they should be private, place their declarations in a private interface). To simplify this task, objective-c uses properties that do not exceed abbreviations. In addition, there are things like key-value-encoding and -service that are activated by properties, but basically these are just abbreviations for getters and seters.

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

0
source

All Articles