简体   繁体   中英

Objective C - Make iVars hidden

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.

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.

您可以在@implementation块中包含一个ivar定义块。

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM