如何知道带有MagicalRecord的NSManagedObjectContext是否为零?

时间:2015-10-29 09:55:44

标签: ios core-data magicalrecord

我在我的应用中使用了MagicalRecord。

当用户退出时,我会

[MagicalRecord cleanUp];

但是一些异步操作仍然从我的后端接收到答案,所以当我的应用程序收到该答案时,它会尝试添加或从我的CoreData模型中获取信息并且崩溃。

如何检查MagicalRecord - NSManagedObjectContext是否为零?

这是我的源代码的一点,我必须检查它:

AFJSONRequestOperation *operationUserData = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

        [mixpanel.people set:[self createMixPanelData:JSON]];

        User *user = (User *)[User findFirst];

        user.isPremium = [JSON valueForKey:@"isPremium"];

        [[NSManagedObjectContext defaultContext] saveToPersistentStoreAndWait];

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {

        NSLog(@"error %@", [error description]);
    }];

当我执行User *user = (User *)[User findFirst];时,它会因以下错误而崩溃:

Default context is nil! Did you forget to initialize the Core Data Stack?

这就是坠毁的行:

    NSManagedObjectContext *defaultContext = [NSManagedObjectContext MR_defaultContext];

我在AppDelegate中创建了一个NSOperationQueue来添加操作。当我注销时,我取消了所有操作,但队列没有清理。

- (void)logOut:(id)sender
{
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    NSLog(@"A- Operation count: %lu", (unsigned long)[appDelegate.queue operationCount]);
    [appDelegate.queue cancelAllOperations];
    NSLog(@"B- Operation count: %lu", (unsigned long)[appDelegate.queue operationCount]);
}

输出:

2015-10-29 14:51:42.251 MyApp[1389:689920] A- Operation count: 527
2015-10-29 14:51:42.256 MyApp[1389:689920] B- Operation count: 527

0 个答案:

没有答案