有些数据没有留在Core Data中

时间:2014-01-23 14:30:04

标签: objective-c core-data entity

我有一个项目,我从多个Web服务中消耗数据,然后将它们存储在Core Data中的不同实体中。确切地说,有4个不同的实体。其中3个存储得很好。 Core Data中的第4个商店和我可以在其他视图中检索它但是如果我关闭应用程序并将其打开备份,则InventoryImage实体似乎是空的。

- (void)viewDidLoad {
    [super viewDidLoad];
    id delegate = [[UIApplication sharedApplication]delegate];
    self.managedObjectContext = [delegate managedObjectContext];

    _isConnected = TRUE;

    [self checkOnlineConnection];
    DealerModel *dealer = [[DealerModel alloc]init];
    [dealer getDealerNumber];
    _dealerNumber = dealer.dealerNumber;
    //_dealerNumber = @"000310";
    if (_isConnected == TRUE) {
        [self downloadInventoryData:_dealerNumber];
        [self downloadImages:_dealerNumber];
    }
    else{
        [self loadInventory];
        [self loadImages];
    }
}

 - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }

/ *表格数据* /

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 1;
    }

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_modelsArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    InventoryCell *cell = (InventoryCell *)[tableView dequeueReusableCellWithIdentifier:[_inventoryCell reuseIdentifier]];

    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"InventoryCell" owner:self options:nil];
        cell = _inventoryCell;
        _inventoryCell = nil;
    }

    InventoryHome *currentHome = [_modelsArray objectAtIndex:indexPath.row];

    NSNumber *imageCount = [self loadImagesBySerialNumber:currentHome.serialNumber];

    cell.lblModelDescription.text = currentHome.homeDesc;
    cell.lblSerialNumber.text = currentHome.serialNumber;
    cell.lblImageCount.text = [NSString stringWithFormat:@"Images: %@", imageCount];

    return cell;
}

/ *结束表数据* /

/ *开始下载* /

 #pragma mark - Inventory and Image Data

- (void)downloadInventoryData:(NSString *)dealerNumber
{
    [self loadInventory];

    if (_isConnected == 1 && [_modelsArray count] > 0) {
        [self clearModelEntity:@"InventoryHome"];
    }

    NSString *urlString = [NSString stringWithFormat:@"%@%@", webServiceInventoryListURL, dealerNumber];
    NSURL *invURL = [NSURL URLWithString:urlString];
    NSData *data = [NSData dataWithContentsOfURL:invURL];

    NSLog(@"Inventory Web Service URL: %@", invURL);

    // Sticks all of the jSON data inside of a dictionary
    _jSON = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

    // Creates a dictionary that goes inside the first data object eg. {data:[
    _dataDictionary = [_jSON objectForKey:@"data"];

    // Check for other dictionaries inside of the dataDictionary
    for (NSDictionary *modelDictionary in _dataDictionary) {

        InventoryHome *home = [NSEntityDescription insertNewObjectForEntityForName:@"InventoryHome" inManagedObjectContext:[self managedObjectContext]];
        NSString *trimmedSerialNumber = [NSString stringWithFormat:@"%@",[NSLocalizedString([modelDictionary objectForKey:@"serialnumber"], nil) stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];

        home.homeDesc = NSLocalizedString([modelDictionary objectForKey:@"description"], nil);
        home.serialNumber = trimmedSerialNumber;
        home.brandDesc = NSLocalizedString([modelDictionary objectForKey:@"branddescription"], nil);
        home.beds = [NSNumber numberWithInt:[NSLocalizedString([modelDictionary objectForKey:@"numberofbedrooms"], nil) intValue]];
        home.baths = [NSNumber numberWithInt:[NSLocalizedString([modelDictionary objectForKey:@"numberofbathrooms"], nil) intValue]];
        home.sqFt = [NSNumber numberWithInt:[NSLocalizedString([modelDictionary objectForKey:@"squarefeet"], nil) intValue]];
        home.length = [NSNumber numberWithInt:[NSLocalizedString([modelDictionary objectForKey:@"length"], nil) intValue]];
        home.width = [NSNumber numberWithInt:[NSLocalizedString([modelDictionary objectForKey:@"width"], nil) intValue]];
    }
    [self loadInventory];
}

- (void)downloadImages:(NSString *)dealerNumber
{
    [self loadImages];

    if (_isConnected == 1 && [_imagesArray count] > 0) {
        [self clearModelEntity:@"InventoryImage"];
    }

    NSString *stringImageURL = [NSString stringWithFormat:@"%@%@",inventoryImageURL, dealerNumber];
    NSURL *url = [NSURL URLWithString:stringImageURL];
    NSData *imageData = [NSData dataWithContentsOfURL:url];

    _jSON = [NSJSONSerialization JSONObjectWithData:imageData options:kNilOptions error:nil];
    _dataDictionary = [_jSON objectForKey:@"data"];

    for (NSDictionary *imageDictionary in _dataDictionary) {
        InventoryImage *image = [NSEntityDescription insertNewObjectForEntityForName:@"InventoryImage" inManagedObjectContext:[self managedObjectContext]];
        NSString *trimmedSerialNumber = [NSString stringWithFormat:@"%@",[NSLocalizedString([imageDictionary objectForKey:@"serialnumber"], nil) stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];

        image.assetID = NSLocalizedString([imageDictionary objectForKey:@"aid"], nil);
        image.sourceURL = NSLocalizedString([imageDictionary objectForKey:@"imagereference"], nil);
        image.serialNumber = trimmedSerialNumber;
        image.group = NSLocalizedString([imageDictionary objectForKey:@"imagegroup"], nil);
        image.imageTagId = [NSString stringWithFormat:@"%@", [imageDictionary objectForKey:@"searchtagid"]];
        image.imagesId = [NSString stringWithFormat:@"%@", [imageDictionary objectForKey:@"imagesid"]];
        image.imageCaption = NSLocalizedString([imageDictionary objectForKey:@"imagecaption"], nil);
        image.imageSource = NSLocalizedString([imageDictionary objectForKey:@"imagesource"], nil);
        image.inventoryPackageID = NSLocalizedString([imageDictionary objectForKey:@"inventorypackageid"], nil);
    }
}

/ *结束下载* /

/ *从核心数据加载库存和图像* /

- (void)loadInventory
{
    _fetchRequest = [[NSFetchRequest alloc]init];
    _entity = [NSEntityDescription entityForName:@"InventoryHome" inManagedObjectContext:[self managedObjectContext]];
    _sort = [NSSortDescriptor sortDescriptorWithKey:@"homeDesc" ascending:YES];
    _sortDescriptors = [[NSArray alloc]initWithObjects:_sort, nil];

    [_fetchRequest setSortDescriptors:_sortDescriptors];
    [_fetchRequest setEntity:_entity];

    NSError *error = nil;

    _modelsArray = [[self managedObjectContext] executeFetchRequest:_fetchRequest error:&error];

    if (![[self managedObjectContext]save:&error]) {
        NSLog(@"An error has occurred: %@", error);
    }

    [self.inventoryListTable reloadData];
}

- (NSNumber *)loadImagesBySerialNumber: (NSString *)serialNumber
{
    _imagesFetchRequest = [[NSFetchRequest alloc]init];
    _imagesEntity = [NSEntityDescription entityForName:@"InventoryImage" inManagedObjectContext:[self managedObjectContext]];
    _imagesPredicate = [NSPredicate predicateWithFormat:@"serialNumber = %@ && group <> 'm-FLP' && imageSource <> 'MDL'", serialNumber];

    [_imagesFetchRequest setEntity:_imagesEntity];
    [_imagesFetchRequest setPredicate:_imagesPredicate];

    NSError *error = nil;
    _imagesArray = [[self managedObjectContext] executeFetchRequest:_imagesFetchRequest error:&error];

    NSNumber *imageCount = [NSNumber numberWithInteger:[_imagesArray count]];

    return imageCount;
}

- (void)loadImages
{
    _imagesFetchRequest = [[NSFetchRequest alloc]init];
    _imagesEntity = [NSEntityDescription entityForName:@"InventoryImage" inManagedObjectContext:[self managedObjectContext]];

    [_imagesFetchRequest setEntity:_imagesEntity];

    NSError *error = nil;

    _imagesArray = [[self managedObjectContext] executeFetchRequest:_imagesFetchRequest error:&error];
}

/ *从核心数据结束加载库存和图像* /

- (void)clearModelEntity:(NSString *)entity
{
    _fetchRequest = [[NSFetchRequest alloc]init];
    _entity = [NSEntityDescription entityForName:entity inManagedObjectContext:[self managedObjectContext]];

    [_fetchRequest setEntity:_entity];

    NSError *error = nil;
    _modelsArray = [[self managedObjectContext] executeFetchRequest:_fetchRequest error:&error];

    for (NSManagedObject *object in _modelsArray) {
        [[self managedObjectContext] deleteObject:object];
    }

    NSError *saveError = nil;
    if (![[self managedObjectContext] save:&saveError]) {
        NSLog(@"An error has occurred: %@", saveError);
    }
}

- (void)clearImageEntity:(NSString *)entity
{
    _fetchRequest = [[NSFetchRequest alloc]init];
    _entity = [NSEntityDescription entityForName:entity inManagedObjectContext:[self managedObjectContext]];

    [_fetchRequest setEntity:_entity];

    NSError *error = nil;
    _imagesArray = [[self managedObjectContext] executeFetchRequest:_fetchRequest error:&error];

    for (NSManagedObject *object in _imagesArray) {
        [[self managedObjectContext] deleteObject:object];
    }

    NSError *saveError = nil;
    if (![[self managedObjectContext] save:&saveError]) {
        NSLog(@"An error has occurred: %@", saveError);
    }
}

1 个答案:

答案 0 :(得分:1)

不要忘记致电[save:conetext]。如果您在未保存的情况下关闭,则会丢失数据。