开发者

difference between property and public

When declaring variables in an interface wha开发者_JAVA百科t is the difference between the two:

@interface thing:NSObject {
    int x;
    int y;
}
@property int x, y;

2:

@interface thing:NSObject {
    @public
    int x;
    int y;
}


The property declaration, and the matching @synthesize statement, will create standard accessors for values named x and y. the public declaration of your instance variables will allow any code in your app to access those values in your instance storage directly.


@public is an access modifier that means you can access an attribute directly like this:

obj->someAttrib;

@property means that compiler should create accessor methods (if you're using @synthesize).

An important thing is that property doesn't necessarily match an attribute. You can create smth like this:

@property(readonly) int doSmth;

and then implement it:

-(int) doSmth {
   return 123+456;
}

However this is very rough and incomplete explanation (there is much more under properties). Read some articles/books about ObjC.


default is @protected so the only difference is if you wanted to access them directly, which is generally considered bad practice, but in the first example you could not do:

thing * aThing = [[thing alloc] init];
aThing->x = 5;

Edit: (as I got voted down by answering the actual question not the implied question.)

In Objective-C there are 3 visibility specifiers: @public; @private; and @protected.

The syntax only affects visibility of iVars, not methods, all methods are publicly visible.

the specifier works for all iVars following until it reaches another specifier;

@public allows direct access of ivars from outside of instances of the class or subclass.

@protected allows direct access of ivars from only in instances of the class or subclasses thereof.

@private allows direct access of ivars from inside of instances of the class, but not subclasses.

as for @property it is a language construct introduced with Objective-C 2.0 that allows you to use the . (dot) accessor for calling methods.

the default behavior is @property int x will reference 2 methods depending if you are using it as an left hand(setter) or right hand(getter) operator, the default getter will be -(int)x; and the default setter will be -(void)setX:(int)x;, @property doesn't in itself create those methods, but allows access to them.

the default behavior can be overridden with the following syntax @property(getter=somethingOtherThanX,setter=somethingOtherThanSetX:)int x;

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜