Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 975
learner2010 Avatar asked Jun 26 '12 14:06

learner2010


People also ask

Can you access as private variable outside of it's class?

Private and Public Access You can read or write to the variable from anywhere within the module, class, or structure, but not from outside it.

How do you access a private variable in child class?

We have used the getter and setter method to access the private variables. Here, the setter methods setAge() and setName() initializes the private variables. the getter methods getAge() and getName() returns the value of private variables.

Can I access private variable in the extension Swift?

In Swift 4, an extension can reach across to a private declaration. This only applies to extensions that live in the same source file as the private declaration. In other words, an entity that is declared private is accessible from within any extensions for that type within the same source file.

Can you access private variables in the same class?

This is perfectly legal. Objects of the same type have access to one another's private variables. This is because access restrictions apply at the class or type level (all instances of a class) rather than at the object level (this particular instance of a class).


1 Answers

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"];
like image 131
Nicolas Bachschmidt Avatar answered Oct 13 '22 01:10

Nicolas Bachschmidt