Jayaprada
Jayaprada

Reputation: 954

Without using property how can we access a variable in another class in iOS?

Upvotes: 0

Views: 125

Answers (4)

balkoth
balkoth

Reputation: 738

The 4 possibles cases that I can think to access a variable are:

1 Declare the variable in class A as public

@public
BOOL _test;

Totally not recommended. If you need a public variable you use a property.

2 Use a property.

@property (readonly, getter = myMehtodName) id myVariable;

3 Use a custom method. In practice it acts the same as a property with readonly attribute. Also you can access it with the dot notation.

4 Use KVC to access the variable. This can be useful when you don't know the name of the property / variable in compilation time. A little example:

NSString *myKey = [self obtainKey];
id myVariable = [self valueForKey:myKey];
if ([myVariable isKindOfClass:[NSString class]]) {
    //Do something
}else {
    //Do another thing
}

Note that key can be either a method name or a variable.

Upvotes: 0

soprof
soprof

Reputation: 326

It is bad practice to declare a public variable without making it a property.

You may also use KVC to access(both read and write) ivar, even if it is readonly.

[instanceOfMyClass valueForKey:@"myIvar"];

I hope someone finds my first stackOverflow answer helpful :)

Upvotes: 2

user2260054
user2260054

Reputation: 522

Well, you can declare variable as public and access it with selector operator, but this is not recommended:

@interface A:NSObject{
@public
int x;
}
@end

...
//Somewhere inside class B
A *a = [[A alloc] init];
a->x;

However it's hard to imagine why it can be better that to use a property.

Upvotes: 0

Tapas Pal
Tapas Pal

Reputation: 7207

@interface Class1
{
@public
    int var; // if you not declare it public by default it'll be protected
}
// methods...
@end

// Inside a Class2 method:
Class1 *obj = ...;
obj->var = 3;

But property approach is far better.

Upvotes: 0

Related Questions