I know it's possible to define public instance variable with @public keyword. However, Objective-C syntax does not allow accessing other class' variable. What features should I expected from @public Ivar? Or how do I access other class' Ivars?
There are two ways to access the instance variable of class: Within the class in instance method by using the object reference ( self ) Using getattr() method.
The instance variables must be declared outside the class methods , and any kind of scope. The instance variables can be marked by the access specifiers. Instance variables cannot be marked by the abstract keyword(abstract keyword only used for the methods).
In Objective-C, instance variables are commonly created with @propertys. An @property is basically an instance variable with a few extra bonus features attached. The biggest addition is that Objective-C will automatically define what's called a setter and a getter for you automatically.
In Objective-C, you always have to explicitly specify the type of variable you're declaring. In Swift, the “var” keyword is used to declare a variable and you don't have to specify the type if it can be inferred from what you're assigning it. Also notice in Swift, we're using the String class as opposed to NSString.
Objective-C, as a superset of C, definitely does allow the access of public instance variables from outside the class's implementation. Now, the reason you may have heard that it isn't allowed is that it is highly discouraged. In most cases, if you want to access an instance variable outside an implementation context, you should be using accessors and mutators (properties).
An Objective-C class really boils down to a plain-old C struct with an isa
field (that's what makes it an object), where the public fields are accessible. Since when we are dealing with instances of classes, we are working a pointer to an object (special struct). Thus, we access public fields using ->
.
Here's an example:
@interface SomebodyIsntEncapsulating : NSBadIdea {
@public
NSString *badIdea;
BOOL shouldntDoIt;
@protected
NSString *ahThatsBetterThankGod;
@private
NSString *sweetThanksNowEvenMySubclassesCantTouchMe;
}
Now, in some completely different context, we could have:
SomebodyIsntEncapsulating *whatOh = [[SomebodyIsntEncapsulating alloc]
initWithDanger:kDangerLevelEpicBraceYourself];
whatOh->badIdea = [@"I'm a public field. Make sure to retain or copy me!" copy];
NSLog(@"Please! Write some accessors and mutators!: %@", whatOh->badIdea);
I hope that helped you!
You can access it like using -> (member by pointer) operator like you normally access members of a c-structure (note that you always have a pointer to an object in obj-c):
...
@public
int a;
...
myObject->a = 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With