开发者

Private instance variables - iPhone SDK

I have a few variables in my iPhone app as class instance variables (which开发者_StackOverflow社区 they need to be because they are used within multiple methods of that class.

However, I don't want them to be exposed to the parent class. I have seen the @private keyword, but I am not sure if this is the appropriate use or not.

Does anyone how to keep instance variables as private to the class?

This is probably an Objective-C question as well, and not necessarily specific to the iphone.

Many thanks, Brett


@private makes your intention clear and is the way to go.

Edit:

@interface YourClass : NSObject {
@private
    int privateData;
@public
    int publicData;
}

// method declarations....

@end


Class instance variables (assuming you mean a variable that can be set in one object and read in another object of the same class) in Objective C are the same as static global variables in plain ANSI C (assuming you put one class implementation inside one .m file).

Static globals won't be exposed to any other class (super, sub, alien, etc.) or code outside the implementation file containing these class instance variables.

The @private declaration stuff in other answers here is most probably incorrect (depending on what you mean by your terminology), as those instance variables won't have class-wide scope, but are private to each individual object (unless exposed by a property).


The @private directive means that the instance variable is accessible only within the class that declares it. If you want a subclass to have access to the instance variables, use the @protected directive. I'm not exactly sure what you mean when you say that you don't want your instance variables exposed to the parent class, but I'm pretty sure that @private is what you want.

You use the directives like this:

@interface MyClass : NSObject {
@private
    float privateFloat;
    float anotherPrivateFloat;
@protected
    float protectedFloat;
@public
    float publicFloat;
}

The default scope for instance variables is protected.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜