I'm trying to declare some instance variables for a custom button class in Objective-C (for iOS):
@interface PatientIDButton : UIButton {
NSUInteger patientID;
NSString * patientName;
}
@end
However, these are now private and I need them accessible to other classes. I guess I could make accessor functions for them, but how would I make the variables themselves public?
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.
Normally, it is recommended to make these variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers. Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null.
In Objective-C, you generally define the @interface in a . h file and include any public methods and properties in that . h file. And then to expose those in your framework, you #include that .
To make instance variables public, use @public
keyword, like this:
@interface PatientIDButton : UIButton {
// we need 'class' level variables
@public NSUInteger patientID;
}
@end
Of course you need to remember all the standard precautions of exposing "raw" variables for public access: you would be better off with properties, because you would retain flexibility of changing their implementation at some later time.
Finally, you need to remember that accessing public variables requires a dereference - either with an asterisk or with the ->
operator:
PatientIDButton *btn = ...
btn->patientID = 123; // dot '.' is not going to work here.
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