Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to declare a public instance variable in Objective-C

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?

like image 331
easythrees Avatar asked Jul 07 '13 02:07

easythrees


People also ask

How do you declare an instance variable in Objective-C?

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.

Should instance variables be public?

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.

How do you make a class public in Objective-C?

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 .


1 Answers

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.
like image 150
Sergey Kalinichenko Avatar answered Oct 20 '22 19:10

Sergey Kalinichenko