关于NSNotification的疑问


我在 AppDelegate.m 里写了几个函数:


 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    debugMethod();
    self.WeiboStatusesDatabaseContext = [self createMainQueueManagedObjectContext];
    return YES;
}

- (void)setWeiboStatusesDatabaseContext:(NSManagedObjectContext *)WeiboStatusesDatabaseContext
{
    debugMethod();
    _WeiboStatusesDatabaseContext = WeiboStatusesDatabaseContext;
    NSDictionary *userInfo = self.WeiboStatusesDatabaseContext ? @{WeiboSTATUSESDatabaseAvailabilityContext : self.WeiboStatusesDatabaseContext} : nil;
    [[NSNotificationCenter defaultCenter] postNotificationName:WeiboSTATUSESDatabaseAvailabilityNotification
                                                    object:self
                                                  userInfo:userInfo];
}

然后在 MainPageCDTVC 里写了 :


 - (void)awakeFromNib
{
    debugMethod();
    [[NSNotificationCenter defaultCenter] addObserverForName:WeiboSTATUSESDatabaseAvailabilityNotification
                                                  object:nil
                                                   queue:nil
                                              usingBlock:^(NSNotification *note) {
                                                  self.managedObjectContext = note.userInfo[WeiboSTATUSESDatabaseAvailabilityContext];
                                                  debugLog(@"context = %@", self.managedObjectContext);
                                              }];
    debugLog(@"Context = %@", self.managedObjectContext);
}

当我将 MainPageCDTVC 作为初始界面并运行后,从控制台得到如下结果:


 2015-04-02 11:37:38.650 WeiboDemo[962:48379] -[MainPageCDTVC awakeFromNib]
2015-04-02 11:37:38.665 WeiboDemo[962:48379] Context = (null)
2015-04-02 11:37:38.669 WeiboDemo[962:48379] -[AppDelegateapplication:didFinishLaunchingWithOptions:]
2015-04-02 11:37:38.673 WeiboDemo[962:48379] file:///Users/wlSong/Library/Developer/CoreSimulator/Devices/7DCCFF56-7A91-4DCC-BB20-CE33FCAE42BF/data/Containers/Data/Application/82C32B6F-A842-4BFD-A9DF-0126A7C290BC/Documents/
2015-04-02 11:37:38.691 WeiboDemo[962:48379] managedObjectContext have created.
2015-04-02 11:37:38.691 WeiboDemo[962:48379] -[AppDelegate setWeiboStatusesDatabaseContext:]
2015-04-02 11:37:38.695 WeiboDemo[962:48379] context = < NSManagedObjectContext: 0x7b84da00 >

我的问题时:
1.context的实例为什么最后才输出?毕竟 -[MainPageCDTVC awakeFromNib] 是先执行的啊。
2.当我把另一个 ViewController 作为初始界面并用一个segue使其跳转到MainPageCDTVC 后,MainPageCDTVC根本没有获得 context.为什么?

ios

一个拉拉人 9 years, 7 months ago

发送notification的时候原来的VC还没注册监听器吧。

易碎D秀吉 answered 9 years, 7 months ago

Your Answer