Rick Royd Aban
Rick Royd Aban

Reputation: 904

How to access protected variables in Objective-C

I want to have a variable that will only be visible to its subclasses which is exactly similar to what protected variables are in Java.

I tried like this on the parent's implementation file

@interface ParentClass (){
   NSArray *_protectedVar
}

but unfortunately the protectedVar is not visible as soon as I call super.protectedVar

Correct my if I am wrong but I don't wanna use @properties to that variable since it will make that variable public.

And this is my subclass's header file looks like @interface SubClass : ParentClass

Upvotes: 1

Views: 2958

Answers (2)

jlehr
jlehr

Reputation: 15597

The code you posted declares an instance variable in an Objective-C class extension, and therefore the variable's default visibility is private. You can use a visibility modifier to change the ivar's visibility, as shown below:

@interface ParentClass ()
{
@protected
    NSArray *_protectedVar
}

Upvotes: 2

Bryan Chen
Bryan Chen

Reputation: 46588

If you have this

ParentClass.h

@interface ParentClass : NSObject{
   NSArray *_protectedVar
}

Then just like how you access normal ivar, use _protectedVar directly.

But I suggest you use property with private header

Parent.h

@interface Parent : NSObject

@property id publicProperty;

@end

Parent_Protected.h

@interface Parent (Protected)

@property id protectedProperty

@end

So normal class only #import "Parent.h", they can't see protected property. But subclass can #import "Parent_Protected.h" and use protected property with self.protectedProperty

Upvotes: -1

Related Questions