Access Variable from Another Class - Objective-C

后端 未结 3 1830
孤独总比滥情好
孤独总比滥情好 2021-01-22 13:15

This question has probably been asked before so I\'m sorry.

I am working on an iPhone app and lets say I have a variable, var, in class1. I want to add a UIButton in cl

相关标签:
3条回答
  • 2021-01-22 13:57

    Use a setter method -setVar: or similar on the class that you want to set the variable in. You can't access instance variables of other objects: they are all private by default.

    0 讨论(0)
  • 2021-01-22 14:03

    Try using a singleton http://developer.apple.com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/Singleton.html If you can't figure it out by reading through that let me know and I'll make an example!

    0 讨论(0)
  • 2021-01-22 14:07

    The problem with the snippet of code you're showing is that NSUserDefaults only writes the values down to disk when the app quits (or probably also when it's sent to the background in iOS 4). If you need to force NSUserDefaults to write the values of the keys to disk, call the [[NSUserDefaults standardUserDefaults] synchronize] method on it.

    Also, instead of using removeObjectForKey: in resetVar, why not using setDouble:forKey: instead? This way you could also get rid of the "double var" ivar in Class1, just using NSUserDefaults as store of the data.

    Here's a bit of info about the synchronize method, from the NSUserDefaults documentation:

    Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.

    This is how I would implement what you described in your code:

    @interface Class1 
    {
    }
    - (void)resetVar;
    @end
    
    @implementation Class1
    - (void)viewDidLoad 
    {
        [self resetVar];
    }
    - (void)resetVar 
    {
        [[NSUserDefaults standardUserDefaults] setDouble:0.0 forKey:@"count"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    @end
    
    @interface Class2 
    { 
        Class1 *classObj;
    }
    - (IBAction)reset:(id)sender;
    @end
    
    @implementation Class2
    - (void)dealloc 
    {
        [classObj release];
    }
    - (void)viewDidLoad 
    {
        classObj = [[Class1 alloc] init];
    }
    - (IBAction)reset:(id)sender 
    {
        [classObj resetVar];
    }
    @end
    
    0 讨论(0)
提交回复
热议问题