Notification Once perfectly solves the initialization of some modules in application:didFinishLaunchingWithOptions

2192 단어 iOS
in the finishing project
AppDelegate , found many written in
- application:didFinishLaunchingWithOptions: The code in is just to get a call opportunity when the program starts, mostly for the initialization of some modules, such as:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // ...
    [RunModule setup];
    [[Loca sharedInstance] setup];
    // ...
    return YES;
}
In fact, these codes can be fully exploited
Notification The way to get it inside your own module, share a clever method:
// RunModule.m
+ (void)load
{
    __block id observer =
    [[NSNotificationCenter defaultCenter]
     addObserverForName:UIApplicationDidFinishLaunchingNotification
     object:nil
     queue:nil
     usingBlock:^(NSNotification *note) {
         [self setup]; // Do whatever you want
         [[NSNotificationCenter defaultCenter] removeObserver:observer];
     }];
}
explain:

  • + load Method called early enough
  • The block version of notification registration produces a __NSObserver * object for external remove observers
  • The block capture of the observer object is earlier than the return of the function, so if __block is not added, it will capture nil
  • Remove observer at end of block execution without additional cleanup
  • In this way, the mounting of the code at the program startup point is completed inside the module

  • It's worth noting that the notification is not sent until the - application:didFinishLaunchingWithOptions: call completes. By the way, here is a suggestion for AppDelegate to slim down: AppDelegate, as a delegate for program-level state changes, should only be used for routing and distribution. The specific logic implementation code should still be in a separate module. This file should be kept clean, except for There should be no other methods outside the method.

    좋은 웹페이지 즐겨찾기