Where and how should I instantiate an object which will be used globally in an IOS app?

后端 未结 3 1283
你的背包
你的背包 2020-12-20 05:48

For simplicity\'s sake, lets say I am making a stopwatch application for ios5. I have a class called stopwatch, which represents the stopwatch\'s state. This class possesses

3条回答
  •  醉梦人生
    2020-12-20 06:30

    If you "declare it to be a member of the AppDelegate class" then you should use it as a property:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:     (NSDictionary *)launchOptions {
        Stopwatch *aStopwatch = [[Stopwatch alloc] init];
        self.stopwatch = aStopwatch;
        [aStopwatch release];
        ...
    }
    

    Later, anywhere in your code:

    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate doSomethingWithStopwatchMethod];
    someVariable = appDelegate.stopwatch.timeSinceStart;
    ...
    

    Another approach would be to use a singleton (check SO for dozens of questions on the subject) or even a plain global variable (an integer holding a flag for instance) declared in main.m.

提交回复
热议问题