objective-cvisibilitypublicivar

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?


Solution

  • 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.