learner2010
learner2010

Reputation: 4167

Accessing private variables from an external class - iOS

I have a private variable in a class and I am trying to access that variable from an external class. Is there a way I could do this?

Upvotes: 8

Views: 8717

Answers (3)

Nicolas Bachschmidt
Nicolas Bachschmidt

Reputation: 6505

The private instance variables are, by definition, private. You cannot access them externally. If you are the author of the class, you should provide accessor methods for the variable. If you're not, you should refrain from accessing the variable.

However, there are ways to circumvent that limitation.

You may create a category on the first class and add an accessor method for the instance variable.

Or your may use Key-Value Coding to access the variable.

[object valueForKey:@"variable_name"];

Upvotes: 27

Dan F
Dan F

Reputation: 17732

Private by definition means it cannot be accessed by an external class. The only real way to get access to private data is through accessor methods provided in the interface.

In objective-c you can create what are called Categories. These are groups of methods that you can basically use to extend the functionality of a class. I am not positive about getting access to private members declared in external classes (ones that you don't have the full implementation for), but I was able to write a category for my own class that accesses a private member.

#import "OtherClass.h"

@interface OtherClass(RandomAccessor)

-(int) getMyVar;

@end

@implementation OtherClass(RandomAccessor)

-(int) getMyVar
{
    return self->myPrivateVar;
}

@end

I don't really recommend doing something like this, though, because developers typically make data private for a reason.

Upvotes: 1

Highrule
Highrule

Reputation: 1915

You can create your own get/set methods...OR you can use the Objective-C standard by declaring the variable as a property in your .h file, and then synthesizing it in your .m file...Keep in mind, if other classes can see the variable and access it, then it's no longer a "private" variable

testViewController.h

@interface testViewController : UIViewController
{
    NSString *someString;
}

@property (nonatomic, retain) NSString *someString;

@end

testViewController.m

#import testViewController.h

@interface testViewController
@synthesize someString=_someString;
@end

Upvotes: 0

Related Questions