iOS应用需要删除才能获取数据

时间:2015-07-26 15:37:35

标签: ios objective-c uitableview

我正在寻找有关此问题的一些信息。

我有一个iOS项目,它使用REST-Kit从远程服务器获取数据。如果我打开iOS模拟器,删除应用程序,然后然后构建并运行,则表格视图将按预期显示。 左图

enter image description here enter image description here

但是,如果我重建并运行而不首先在模拟器中删除应用程序,则没有抛出错误,但tableview中的单元格为空。 正确的图片

以前有人有这个问题吗?如何在不先删除应用程序的情况下正确显示数据!谢谢你的阅读!

来自app delegate的代码,用于初始化核心数据并定义JSON和核心数据之间的映射。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSLog(@"App started");

// Initialise RestKit
NSURL *baseURL = [NSURL URLWithString:@"http://*.*.*.*/"];
RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:baseURL];


// Initialize managed object model from bundle
NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];

// Initialize managed object store
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];

NSError *error = nil;
BOOL success = RKEnsureDirectoryExistsAtPath(RKApplicationDataDirectory(), &error);
if(! success){
    RKLogError(@"Failed to create application directory at path '%@': %@", RKApplicationDataDirectory(), error);
}


[objectManager setAcceptHeaderWithMIMEType:RKMIMETypeJSON];


// Complete core data store initialization
[managedObjectStore createPersistentStoreCoordinator];
NSString *storePath = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"EventsDB.sqlite"];
NSString *seedPath = [[NSBundle mainBundle] pathForResource:@"RKSeedDatabase" ofType:@"sqlite"];
NSPersistentStore *persistantStore = [managedObjectStore addSQLitePersistentStoreAtPath:storePath fromSeedDatabaseAtPath:seedPath withConfiguration:nil options:nil error:&error];
NSAssert(persistantStore, @"Failed to add persistent with error %@", error);

objectManager.managedObjectStore = managedObjectStore;

// Create the managed object contexts
[managedObjectStore createManagedObjectContexts];

// Configure a managed object cache to ensure we don't create duplicate objects
managedObjectStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:managedObjectStore.persistentStoreManagedObjectContext];


// If a data request fails we should send an NSError message
RKObjectMapping *errorMapping = [RKObjectMapping mappingForClass:[RKErrorMessage class]];
[errorMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:nil toKeyPath:@"errorMessage"]];
RKResponseDescriptor *errorDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:errorMapping pathPattern:nil keyPath:@"error" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassClientError)];
[objectManager addResponseDescriptorsFromArray:@[errorDescriptor]];

// Map event
RKEntityMapping *eventMapping = [RKEntityMapping mappingForEntityForName:@"Event" inManagedObjectStore:managedObjectStore];
eventMapping.identificationAttributes = @[@"eventId"];
[eventMapping addAttributeMappingsFromDictionary:@{//@"JSON":@"MODEL"
                                                   @"_id":@"eventId",
                                                   @"name":@"name",
                                                   @"venue":@"venue",
                                                   @"drink_prices":@"prices",
                                                   @"popularity":@"popularity",
                                                   @"genre":@"genre",
                                                   @"promotionQuote":@"promotionQuote",
                                                   @"dress_code":@"dressCode",
                                                   @"opening_time":@"openingTime",
                                                   @"closing_time":@"closingTime",
                                                   @"critic_review":@"criticReview",
                                                   @"critic_rating":@"criticRating",
                                                   @"image":@"imageURL",
                                                   @"published":@"published"
                                                   }];


// Map drink deals
RKEntityMapping *dealMapping = [RKEntityMapping mappingForEntityForName:@"Deal" inManagedObjectStore:managedObjectStore];
dealMapping.identificationAttributes = @[@"dealId"];
[dealMapping addAttributeMappingsFromDictionary:@{ //@"JSON":@"MODEL"

                                                   @"_id":@"dealId",
                                                   @"description":@"dealDescription",
                                                   @"price":@"price"

                                                   }];

// Map entries
RKEntityMapping *entryMapping = [RKEntityMapping mappingForEntityForName:@"Entry" inManagedObjectStore:managedObjectStore];
entryMapping.identificationAttributes = @[@"entryId"];
[entryMapping addAttributeMappingsFromDictionary:@{ //@"JSON":@"MODEL"

                                                   @"_id":@"entryId",
                                                   @"type":@"type",
                                                   @"price":@"price"

                                                   }];

// Map guestliest -- reviews, city and university come off a guestlisted user
RKEntityMapping *guestlistMapping = [RKEntityMapping mappingForEntityForName:@"User" inManagedObjectStore:managedObjectStore];
guestlistMapping.identificationAttributes = @[@"userId"];
[guestlistMapping addAttributeMappingsFromDictionary:@{//@"JSON":@"MODEL"
                                                   @"_id":@"userId",
                                                   @"name":@"name",
                                                   }];
// Map vip extras
RKEntityMapping *vipMapping = [RKEntityMapping mappingForEntityForName:@"VIP" inManagedObjectStore:managedObjectStore];
vipMapping.identificationAttributes = @[@"vipId"];
[vipMapping addAttributeMappingsFromDictionary:@{ //@"JSON":@"MODEL"

                                                   @"_id":@"vipId",
                                                   @"type":@"type",
                                                   @"available":@"available"

                                                   }];
// EventList Mapping
RKEntityMapping *eventListMapping = [RKEntityMapping mappingForEntityForName:@"EventList" inManagedObjectStore:managedObjectStore];


// Register relationships
[eventListMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"events" toKeyPath:@"events" withMapping:eventMapping]];
[eventMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"drink_deals" toKeyPath:@"deals" withMapping:dealMapping]];
[eventMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"entry" toKeyPath:@"entries" withMapping:entryMapping]];
[eventMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"guestlist" toKeyPath:@"guestlist" withMapping:guestlistMapping]];
[eventMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"vipExtras" toKeyPath:@"vipExtras" withMapping:vipMapping]];

// Regiseter event mapping with the provider. Do i have to do this for all 4 event maps?
RKResponseDescriptor *eventListResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:eventListMapping
                                                                                             method:RKRequestMethodGET
                                                                                        pathPattern:@"api/event.json"
                                                                                                keyPath:nil
                                                                                        statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];


[objectManager addResponseDescriptor:eventListResponseDescriptor];

NSLog(@"objMan responseDescriptors->%@", objectManager.responseDescriptors);

// enable activity indicator spinner
[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

// Map
return YES;
}

获取数据的代码

-(void)requestData {

NSLog(@"requesting data");


NSString *requestPath = @"api/event.json";

[[RKObjectManager sharedManager]
    getObjectsAtPath:requestPath
        parameters:nil
            success: ^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                // events have been saved in core data by now
                NSLog(@"Success");

                [self fetchEventsFromContext];
                }
            failure: ^(RKObjectRequestOperation *operation, NSError *error){
                RKLogError(@"Load failed with error: %@", error);
                NSLog(@"Fail");

                }
 ];

}



-(void)fetchEventsFromContext {

    NSManagedObjectContext *context = [RKManagedObjectStore defaultStore].mainQueueManagedObjectContext;
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"EventList"];

    if(!context) exit(-1);
    if(!fetchRequest) exit(-1);

    //NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"popularity" ascending:YES];
    fetchRequest.sortDescriptors = nil;//@[descriptor];

    NSError *error = nil;
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest  error:&error];

    EventList *eventList = [fetchedObjects firstObject];

    self.events = [eventList.events allObjects];

    if(!self.events){NSLog(@"No events");}

    [self.tableView reloadData];
    NSLog(@"reloading data");


    }

**呈现表格单元格的代码**

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSLog(@"rendering cells");

    MasterTableCellTableViewCell *cell = (MasterTableCellTableViewCell *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MasterTableCell" ];
    if(!cell)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MasterTableCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }

    NSLog(@"Got here");
    NSLog(@"self.events[indexPath.row]->%@", self.events[indexPath.row]);

    tableView.rowHeight = 160;
    Event *event = self.events[indexPath.row];

    NSString *imageURL = event.imageURL;
    [cell.backgroundImageView sd_setImageWithURL:[NSURL URLWithString:imageURL]];
    cell.eventLocationLabel.text = event.venue;
    cell.eventNameLabel.text = event.name;
    cell.criticRatingLabel.text = @"Critic Rating";
    // cell.criticRatingValue. = event.criticRating; // How to display a number?
    cell.userRatingLabel.text = @"User Rating";
    cell.userRatingValue.text = @"X";

    NSLog(@"Finished assigning cell deets");


    return cell;
}

0 个答案:

没有答案