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

后端 未结 3 1284
你的背包
你的背包 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.

    0 讨论(0)
  • 2020-12-20 06:42
    1. Don’t use a singleton. There are plenty of reasons why singletons are a bad design decision in most cases, I wrote a blog post about some of them.

    2. Don’t store arbitrary data in the app delegate. That’s just misusing an existing singleton to do what you want. The app delegate should be concerned with the app’s lifecycle events, it should not be a place to stick whatever data you want accessible from everywhere.

    One possible correct approach to solve this problem is to have a class that will create you application’s object graph for you and pass the instances to all interested classes. My app delegate’s application did finish launching method mostly look like this:

    - (BOOL) applicationDidFinishWhatever
    {
        Factory *factory = [[Factory alloc] init];
        [self setWindow:[factory buildMainWindow]];
        [window makeKeyAndSomething];
        return YES;
    }
    

    And all the object creation and assembly gets done in the Factory class. The Factory will create the timer (and keep the single instance in memory, if needed) and it will pass the timer to view controllers:

    - (void) buildMainWindow
    {
        UIWindow *window = …;
        [window setRootViewController:[self buildMainController]];
        return window;
    }
    
    - (void) buildMainController
    {
        UIViewController *controller = …;
        [controller setTimer:[self buildTimer]];
        return controller;
    }
    

    I have created a sample Xcode project that shows how to wire an app without singletons. It’s very simple right now, I will add some common use cases later.

    0 讨论(0)
  • 2020-12-20 06:50

    You can use Singleton pattern. look here for more info What should my Objective-C singleton look like?

    0 讨论(0)
提交回复
热议问题