问题
Here's my question.
Let's say I have a class called WebServiceBase.h. And I need to add a iVar in to that class called NSString *requestData. But I don't need to add that iVar in to the header file and make it visible to the external people. (If I'm distributing this as a class library)
Also I need to be able to access this requestData iVar, within the other classes that is extended from the WebServiceBase.h. (These extended classes are written by me. Not from the external people)
I tried with declaring the requestData iVar within the class extensions. But then it's not visible to the extended classes.
Any solution for this? I need to protect my data and make it hide from the external world.
回答1:
You can define your ivars as protected via the @protected
keyword, meaning that your class and all subclasses can access it without any problem, but the compiler won't allow this for other classes which don't inherit from your base class:
@interface Foo : NSObject
{
@protected
NSObject *a;
}
Its as simple as that and already gives you all the safety you can get from Objective-C.
回答2:
You can have an ivar definition block in the @implementation block.
回答3:
there are 2 ways , you can choose one you like.
1).h file
@interface YourClass
{
}
.m file
@interface YourClass ()
@property (nonatomic, retain) NSString *title;
@end
@implementation YourClass
@synthesize title;
//your method
2) .h flie
@interface YourClass
{
}
.m file
@implementation YourClass
{
NSString *title;
}
//your method
回答4:
Declare a class extension that defines the ivar in another .h file. Call it something like myclass-private.h
. Then import that header in both your main class your subclasses.
来源:https://stackoverflow.com/questions/11707495/objective-c-make-ivars-hidden