Objective-c, how to access an instance variable from another class

后端 未结 4 1682
耶瑟儿~
耶瑟儿~ 2020-12-28 23:13

I am used to programming in Java and to use class variables to access data from other classes. Then I found out that class variables does not work the same way in Obj-C, and

4条回答
  •  有刺的猬
    2020-12-29 00:01

    A public class variable in Java is equivalent to a global variable in C and Objective-C. You would implement it as:

    class1.h

    extern NSString* MyGlobalPassword;
    

    class1.m

    NSString* MyGlobalPassword = nil;
    

    Then, anyone that imports class1.h can read and write to MyGlobalPassword.

    A slightly better approach would be make it accessible via a "class method".

    class1.h:

    @interface Class1 : UIViewController {
        UITextField *usernameField;
        UITextField *passwordField;
        UIButton *loginButton;    
    }
    + (NSString*)password;
    @end
    

    class1.m:

    static NSString* myStaticPassword = nil;
    
    @implementation Class1
    + (NSString*)password {
        return myStaticPassword;
    }
    
    - (void)didClickLoginButton:(id)sender {
        [myStaticPassword release];
        myStaticPassword = [passwordField.text retain];
    }
    

    Other classes would then read the password through the password class method.

    Class2.m :

    -(void) someMethodUsingPassword {
         thePassword = [Class1 password]; // This is how to call a Class Method in Objective C
         NSLog(@"The password is: %@", thePassword); 
    }
    

提交回复
热议问题