CoreData 对象未在屏幕之间保存

CoreData objects not saved between screens

我有一个包含 UITableView 的屏幕,在这个屏幕中我有一个 NSManagedObjects 数组。它工作得很好,但是当我尝试移动到另一个屏幕(单击特定单元格,然后推送一个新屏幕),然后 return 到同一个 UITableView 屏幕时,所有对象都丢失了。

这是什么意思?我尝试打印 NSManagedObjects 的数组,它很好,那里的所有对象,但是当我打印每个对象的描述时,我从所有对象属性中得到 nil

有人知道这是什么原因吗?我不知道为什么,但它在 12 小时前工作得很好,但现在一切都搞砸了,我不知道我做了什么。

提前致谢!

保存方式:

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
        else {
            NSLog(@"Context saved!");
        }
    }
}

这是我保存对象的方式:

NSDictionary *response = responseObject;
if ([[response valueForKey:@"status"] rangeOfString:@"ok"].location != NSNotFound)
{
   NSArray *data = [response objectForKey:@"data"];
   if (data.count != 0)
   {
       if (page.integerValue == 0) {
           [[DownloadData sharedData] deleteAllObjectsFromEntityName:@"DbHomeCuisine"];
           [[DownloadData sharedData] deleteAllObjectsFromEntityName:@"DbHomeCategory"];
           [[DownloadData sharedData] deleteAllObjectsFromEntityName:@"DbHomeDish"];
       }

       NSMutableArray *homePageObjects = [[NSMutableArray alloc] initWithCapacity:data.count];
       for (NSDictionary *object in data)
       {
           NSNumber *type = [object objectForKey:@"type"];
           switch (type.integerValue) {
               case 1:
               {
                   NSDictionary *content = [object objectForKey:@"content"];
                   NSManagedObjectContext *context = [[MainDb sharedDb] managedObjectContext];
                   DbHomeCuisine *homeCuisine = [NSEntityDescription insertNewObjectForEntityForName:@"DbHomeCuisine" inManagedObjectContext:context];
                   NSInteger cuisineId = [[content valueForKey:@"cuisine_id"] integerValue];
                   homeCuisine.cuisine = [self gCuisineWithCuisineId:[NSNumber numberWithInteger:cuisineId]];
                   NSInteger count = [[content valueForKey:@"count"] integerValue];
                   homeCuisine.count = [NSNumber numberWithInteger:count];
                   homeCuisine.type = type;
                   [homePageObjects addObject:homeCuisine];
               }
                   break;

               case 2:
               {
                   NSDictionary *content = [object objectForKey:@"content"];
                   NSManagedObjectContext *context = [[MainDb sharedDb] managedObjectContext];
                   DbHomeCategory *homeCategory = [NSEntityDescription insertNewObjectForEntityForName:@"DbHomeCategory" inManagedObjectContext:context];
                   NSInteger categoryId = [[content valueForKey:@"category_id"] integerValue];
                   homeCategory.category = [self gCategoryWithCategoryId:[NSNumber numberWithInteger:categoryId]];
                   NSInteger count = [[content valueForKey:@"count"] integerValue];
                   homeCategory.count = [NSNumber numberWithInteger:count];
                   homeCategory.type = type;
                   [homePageObjects addObject:homeCategory];
               }
                   break;

               case 3:
               {
                   NSDictionary *content = [object objectForKey:@"content"];
                   NSManagedObjectContext *context = [[MainDb sharedDb] managedObjectContext];
                   DbHomeDish *homeDish = [NSEntityDescription insertNewObjectForEntityForName:@"DbHomeDish" inManagedObjectContext:context];
                   homeDish.dishId          = [self gInt:content forKey:@"dish_id"];
                   homeDish.headline        = [AppUtils checkForEmptyValue:[content valueForKey:@"title"]];
                   homeDish.text            = [AppUtils checkForEmptyValue:[content valueForKey:@"description"]];
                   homeDish.cuisineId       = [self gInt:content forKey:@"cuisine_id"];
                   homeDish.cuisine         = [self gCuisineWithCuisineId:homeDish.cuisineId];
                   homeDish.creationDate    = [AppUtils checkForEmptyValue:[content valueForKey:@"creation_time"]];
                   homeDish.userId          = [self gInt:content forKey:@"user_id"];
                   homeDish.longitude       = [self gDouble:content forKey:@"lng"];
                   homeDish.latitude        = [self gDouble:content forKey:@"lat"];
                   homeDish.lastPromoteDate = [AppUtils checkForEmptyValue:[content valueForKey:@"last_promote_time"]];
                   homeDish.price           = [self gInt:content forKey:@"price"];
                   homeDish.currency        = [AppUtils checkForEmptyValue:[content valueForKey:@"currency"]];
                   homeDish.countryName     = [AppUtils checkForEmptyValue:[content valueForKey:@"country_name"]];
                   homeDish.baseCurrency    = [self gFloat:content forKey:@"base_currency"];
                   homeDish.exchangeRate    = [self gFloat:content forKey:@"exchange_rate"];
                   homeDish.countryIsoCode  = [AppUtils checkForEmptyValue:[content valueForKey:@"country_iso_code"]];
                   homeDish.mainPhoto       = [AppUtils checkForEmptyValue:[content valueForKey:@"main_photo"]];
                   homeDish.like            = [self gLikeWithDishId:homeDish.dishId];
                   homeDish.profileImageURL = [AppUtils checkForEmptyValue:[content valueForKey:@"profile_img_url"]];
                   homeDish.likeCount       = [self gInt:content forKey:@"likes"];
                   homeDish.type            = type;
                   [homePageObjects addObject:homeDish];
               }
                   break;

               default:
                   break;
           }
       }

       //   @@log -- Save data to core data and device
       //
       //
       [[MainDb sharedDb] saveContext];

       if (success) {
           success(operation, homePageObjects);
       }
   }
}

说真的,您应该考虑使用 NSFetchedResultsController 进行重构。从Xcode中提供的模板开始(New Project -> Master/Detail -> 检查Core Data,代码在MasterViewController.m中)。

我强烈反对将 Core Data 对象加载到数组中以显示在 table 视图中。您的问题是此类设置的典型问题,您最终也会 运行 遇到内存和性能问题。