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

后端 未结 4 1698
耶瑟儿~
耶瑟儿~ 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-28 23:54

    You should rethink how your app structure is set up. Your basic need is that you need to save your password in one class and access it in another, right? NSUserDefaults is perfect (almost perfect, see note #3 below) for this. Change your class1 code to look like this:

    -(IBAction) loginButtonPushed {
        NSString *username = self.usernameField.text;
        NSString *password = self.passwordField.text;
    
        // Do your login stuff here, if successful do the following
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefauls];
        [defaults setObject:username forKey:@"usernameKey"];
        [defaults setObject:password forKey:@"passwordKey"];
    }
    

    Get rid of your password property, you don't need it for anything now. Also, get rid of your +(NSString *)password; class method.

    When you need to access the login and password:

    -(void) someMethodUsingPassword {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefauls];
        NSString *username = [defaults stringForKey:@"usernameKey"];
        NSString *password = [defaults stringForKey:@"passwordKey"];
    
        // do whatever here
    }
    

    A few notes

    1. I wrote this from memory, so they may have errors if you spot any let me know and I'll update my answer.
    2. You seem to be missing a few key points about how to use class methods and properties. I highly recomend reading Apple's Introduction to Objective-C.
    3. Storing login and password information in NSUserDefaults is NOT secure. If someone gains root access to your device or to your device backups, they may be able to extract this login information. If security is crucial to you, store the login information in Keychain.

提交回复
热议问题