视图加载后,UITableView中的单元格将变为空白

时间:2014-04-14 04:40:15

标签: core-data uitableview

我正在调用来自Web服务的数据,将其存储到CoreData中,然后将其放入我用来填充tableview的数组中。当视图加载时,我将删除CoreData中实体中保存的所有数据,因为来自Web服务的数据将经常更新并且可能来自多个平台。如果没有删除代码,一切正常(除了旧数据会在CoreData中构建),但是一旦我实现deleteEntityData调用,我就会在模拟器上发生这种奇怪的事情。数据出现然后立即消失,就像在tableview加载之前和之后调用删除代码一样。使用NSLogs检查代码似乎是以正确的顺序触发(并且至少根据NSLogs,删除代码没有触发两次)..

这是一个截屏视频的链接,以便您可以看到我在模拟器上看到的内容。

http://youtu.be/kvDynYQPln8

tableview中主要方法的代码如下:

- (void)viewDidLoad{
[super viewDidLoad];
[self setUpData];
}


- (void) deleteEntityData {

//Delete All Old Exlpore View Entities in Core Data

NSLog(@"Delete code being called");

NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
[fetch setEntity:[NSEntityDescription entityForName:@"HomeView" inManagedObjectContext:context]];
[fetch setIncludesPropertyValues:NO];

NSError *error = nil;
NSArray *entities = [context executeFetchRequest:fetch error:&error];
for (NSManagedObject * exploreView in entities) {
    [context deleteObject:exploreView];
}

if (![context save:&error]) {
    NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
};

[self.tableView reloadData];
}




- (void) setUpData {

//Initialize AFHTTPRequestOperationManager with Dribbble API base URL
_operationManager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.karmo.com/home/news"]];

[_operationManager GET:@"?user_id=XXXX" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

    //Success - Runs if connection is made and data recieved
    [self deleteEntityData];

    //Extrat parsed JSON file into objects to prepare for Core Data import -- Should verify if I can skip and go directly into Core Data
    NSManagedObjectContext *context = [self managedObjectContext];


    for (int i = 0; i < [[responseObject valueForKey:@"userBeliefs"] count]; i++) {

        NSString * type = @"user";
        NSString * userFirstName = [[[[responseObject valueForKey:@"userBeliefs"]objectAtIndex:i] valueForKey:@"user"] valueForKey:@"firstName"];
        NSString * userLastName = [[[[responseObject valueForKey:@"userBeliefs"]objectAtIndex:i] valueForKey:@"user"] valueForKey:@"lastName"];
        NSString * userID = [[[[responseObject valueForKey:@"userBeliefs"]objectAtIndex:i] valueForKey:@"user"] valueForKey:@"_id"];
        NSString * topicID = [[[[responseObject valueForKey:@"userBeliefs"]objectAtIndex:i] valueForKey:@"topic"] valueForKey:@"_id"];
        NSString * title = [[[[responseObject valueForKey:@"userBeliefs"]objectAtIndex:i] valueForKey:@"topic"] valueForKey:@"title"];
        NSString * vote = [[[responseObject valueForKey:@"userBeliefs"]objectAtIndex:i] valueForKey:@"vote"];
        NSString * voice = [[[responseObject valueForKey:@"userBeliefs"]objectAtIndex:i] valueForKey:@"voice"];
        NSString * beliefID = [[[responseObject valueForKey:@"userBeliefs"]objectAtIndex:i] valueForKey:@"_id"];
        NSNumber * nPoints = @([[[[responseObject valueForKey:@"userBeliefs"]objectAtIndex:i] valueForKey:@"nPoints"]intValue]);
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
        NSDate *updatedAt = [dateFormat dateFromString:[[[responseObject valueForKey:@"userBeliefs"]objectAtIndex:i] valueForKey:@"updatedAt"]];

        NSManagedObject *newHome = [NSEntityDescription insertNewObjectForEntityForName:@"HomeView" inManagedObjectContext:context];

        [newHome setValue:type forKey:@"type"];
        [newHome setValue:userFirstName forKey:@"userFirstName"];
        [newHome setValue:userLastName forKey:@"userLastName"];
        [newHome setValue:userID forKey:@"userID"];
        [newHome setValue:topicID forKey:@"topicID"];
        [newHome setValue:title forKey:@"title"];
        [newHome setValue:vote forKey:@"vote"];
        [newHome setValue:voice forKey:@"voice"];
        [newHome setValue:beliefID forKey:@"beliefID"];
        [newHome setValue:nPoints forKey:@"nPoints"];
        [newHome setValue:updatedAt forKey:@"updatedAt"];


    }


    for (int i = 0; i < [[responseObject valueForKey:@"followeeBeliefs"] count]; i++) {

        NSUInteger arrayCount = [[[responseObject valueForKey:@"followeeBeliefs"] objectAtIndex:i] count];
        NSUInteger subtract = 2;
        NSUInteger finalCount = arrayCount - subtract;

        for (int ii = 0; ii < finalCount; ii++)  {

            NSString * type = @"followee";
            NSString * followeeUserID = [[[responseObject valueForKey:@"followeeBeliefs"]objectAtIndex:i] valueForKey:@"followee"];
            NSString * connectionID = [[[responseObject valueForKey:@"followeeBeliefs"]objectAtIndex:i] valueForKey:@"_id"];
            NSString * userFirstName = [[[[[responseObject valueForKey:@"followeeBeliefs"]objectAtIndex:i] valueForKey:[@(ii) stringValue]] valueForKey:@"user"] valueForKey:@"firstName"];
            NSString * userLastName = [[[[[responseObject valueForKey:@"followeeBeliefs"]objectAtIndex:i] valueForKey:[@(ii) stringValue]] valueForKey:@"user"] valueForKey:@"lastName"];
            NSString * userID = [[[[[responseObject valueForKey:@"followeeBeliefs"]objectAtIndex:i] valueForKey:[@(ii) stringValue]] valueForKey:@"user"] valueForKey:@"_id"];
            NSString * topicID = [[[[[responseObject valueForKey:@"followeeBeliefs"]objectAtIndex:i] valueForKey:[@(ii) stringValue]] valueForKey:@"topic"] valueForKey:@"_id"];
            NSString * title = [[[[[responseObject valueForKey:@"followeeBeliefs"]objectAtIndex:i] valueForKey:[@(ii) stringValue]] valueForKey:@"topic"] valueForKey:@"title"];
            NSString * vote = [[[[responseObject valueForKey:@"followeeBeliefs"]objectAtIndex:i] valueForKey:[@(ii) stringValue]] valueForKey:@"vote"];
            NSString * voice = [[[[responseObject valueForKey:@"followeeBeliefs"]objectAtIndex:i] valueForKey:[@(ii) stringValue]] valueForKey:@"voice"];
            NSString * beliefID = [[[[responseObject valueForKey:@"followeeBeliefs"]objectAtIndex:i] valueForKey:[@(ii) stringValue]] valueForKey:@"_id"];
            NSNumber * nPoints = @([[[[[responseObject valueForKey:@"followeeBeliefs"]objectAtIndex:i] valueForKey:[@(ii) stringValue]] valueForKey:@"nPoints"]intValue]);
            NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
            [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
            NSDate *updatedAt = [dateFormat dateFromString:[[[[responseObject valueForKey:@"followeeBeliefs"]objectAtIndex:i] valueForKey:[@(ii) stringValue]] valueForKey:@"updatedAt"]];

            NSManagedObject *newHome = [NSEntityDescription insertNewObjectForEntityForName:@"HomeView" inManagedObjectContext:context];

            [newHome setValue:type forKey:@"type"];
            [newHome setValue:followeeUserID forKey:@"followeeUserID"];
            [newHome setValue:connectionID forKey:@"connectionID"];
            [newHome setValue:userFirstName forKey:@"userFirstName"];
            [newHome setValue:userLastName forKey:@"userLastName"];
            [newHome setValue:userID forKey:@"userID"];
            [newHome setValue:topicID forKey:@"topicID"];
            [newHome setValue:title forKey:@"title"];
            [newHome setValue:vote forKey:@"vote"];
            [newHome setValue:voice forKey:@"voice"];
            [newHome setValue:beliefID forKey:@"beliefID"];
            [newHome setValue:nPoints forKey:@"nPoints"];
            [newHome setValue:updatedAt forKey:@"updatedAt"];

        }

    }


    for (int i = 0; i < [[responseObject valueForKey:@"topics"] count]; i++) {

        NSString * type = @"topic";
        NSString * topicID = [[[responseObject valueForKey:@"topics"]objectAtIndex:i] valueForKey:@"_id"];
        NSString * category = [[[responseObject valueForKey:@"topics"]objectAtIndex:i] valueForKey:@"category"];
        NSString * title = [[[responseObject valueForKey:@"topics"]objectAtIndex:i] valueForKey:@"title"];
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
        NSDate *updatedAt = [dateFormat dateFromString:[[[responseObject valueForKey:@"topics"]objectAtIndex:i] valueForKey:@"updatedAt"]];
        NSString * eventTitle = [[[[responseObject valueForKey:@"topics"]objectAtIndex:i] valueForKey:@"lastEvent"] valueForKey:@"title"];
        NSString * eventBody = [[[[responseObject valueForKey:@"topics"]objectAtIndex:i] valueForKey:@"lastEvent"] valueForKey:@"body"];
        NSString * eventID = [[[[responseObject valueForKey:@"topics"]objectAtIndex:i] valueForKey:@"lastEvent"] valueForKey:@"_id"];
        NSDate * eventUpdatedAt = [dateFormat dateFromString:[[[[responseObject valueForKey:@"topics"]objectAtIndex:i] valueForKey:@"lastEvent"] valueForKey:@"updatedAt"]];
        NSDate * eventCreatedAt = [dateFormat dateFromString:[[[[responseObject valueForKey:@"topics"]objectAtIndex:i] valueForKey:@"lastEvent"] valueForKey:@"updatedAt"]];

        NSManagedObject *newHome = [NSEntityDescription insertNewObjectForEntityForName:@"HomeView" inManagedObjectContext:context];

        [newHome setValue:type forKey:@"type"];
        [newHome setValue:topicID forKey:@"topicID"];
        [newHome setValue:category forKey:@"category"];
        [newHome setValue:title forKey:@"title"];
        [newHome setValue:updatedAt forKey:@"updatedAt"];
        [newHome setValue:eventTitle forKey:@"eventTitle"];
        [newHome setValue:eventBody forKey:@"eventBody"];
        [newHome setValue:eventID forKey:@"eventID"];
        [newHome setValue:eventUpdatedAt forKey:@"eventUpdatedAt"];
        [newHome setValue:eventCreatedAt forKey:@"eventCreatedAt"];


    }


    NSError *error = nil;
    if (![context save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }


} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    //Failure

    NSLog(@"Failed to fetch shots from Karmo API!");
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Unable to Connect"
                                                   message:@"We were not able to connect to the karmo database. Some data may be out of date."
                                                  delegate:self
                                         cancelButtonTitle:@"Ok"
                                         otherButtonTitles: nil];
    [alert show];

} ];


[self fetchData];}





- (void) fetchData {

[homeSortData removeAllObjects];
[homeTableData removeAllObjects];

// Fetch the recipes from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"HomeView"];
homeSortData = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

NSSortDescriptor *dateDescriptor = [NSSortDescriptor
                                    sortDescriptorWithKey:@"updatedAt"
                                    ascending:YES];

NSMutableArray * descriptors = [[NSArray arrayWithObjects:dateDescriptor, nil]mutableCopy];
homeTableData  = [[homeSortData sortedArrayUsingDescriptors:descriptors]mutableCopy];
[self.tableView reloadData];}





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

if ([[[homeTableData objectAtIndex:indexPath.row] valueForKey:@"type"] isEqualToString:@"topic"]) {

    HomeTopicUpdateTableViewCell *topicCell = (HomeTopicUpdateTableViewCell *) [tableView dequeueReusableCellWithIdentifier:@"Topic" forIndexPath:indexPath];


    NSDate * topicDate = [[homeTableData objectAtIndex:indexPath.row] valueForKey:@"updatedAt"];
    NSString *currentDateString;
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
    currentDateString = [dateFormat stringFromDate:[NSDate date]];
    NSDate *currentDate = [dateFormat dateFromString:currentDateString];
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *dayComponents = [gregorianCalendar components:NSDayCalendarUnit
                                                           fromDate:topicDate
                                                             toDate:currentDate
                                                            options:0];
    NSString *dayDifference = [NSString stringWithFormat:@"%@d", [@([dayComponents day]) stringValue]];

    [topicCell.title setText:[[homeTableData objectAtIndex:indexPath.row] valueForKey:@"title"]];
    [topicCell.days setText:dayDifference];
    [topicCell.eventTitle setText:[[homeTableData objectAtIndex:indexPath.row]valueForKey:@"eventTitle"]];

    return topicCell;

}

if ([[[homeTableData objectAtIndex:indexPath.row] valueForKey:@"type"] isEqualToString:@"user"]) {

    HomeBeliefTableViewCell *userCell = (HomeBeliefTableViewCell *) [tableView dequeueReusableCellWithIdentifier:@"User" forIndexPath:indexPath];


    NSDate * topicDate = [[homeTableData objectAtIndex:indexPath.row] valueForKey:@"updatedAt"];
    NSString *currentDateString;
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
    currentDateString = [dateFormat stringFromDate:[NSDate date]];
    NSDate *currentDate = [dateFormat dateFromString:currentDateString];
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *dayComponents = [gregorianCalendar components:NSDayCalendarUnit
                                                           fromDate:topicDate
                                                             toDate:currentDate
                                                            options:0];
    NSString *dayDifference = [NSString stringWithFormat:@"%@d", [@([dayComponents day]) stringValue]];
    NSString *pointCount = [[[homeTableData objectAtIndex:indexPath.row] valueForKey: @"nPoints"]stringValue];


    [userCell.title setText:[[homeTableData objectAtIndex:indexPath.row] valueForKey:@"title"]];
    [userCell.belief setText:[[homeTableData objectAtIndex:indexPath.row] valueForKey:@"voice"]];
    [userCell.points setText:pointCount];
    [userCell.profileName setText:@"Me"];
    [userCell.days setText:dayDifference];


    return userCell;


} else {

    HomeFolloweeBeliefTableViewCell *followeeCell = (HomeFolloweeBeliefTableViewCell *) [tableView dequeueReusableCellWithIdentifier:@"Followee" forIndexPath:indexPath];


    NSDate * topicDate = [[homeTableData objectAtIndex:indexPath.row] valueForKey:@"updatedAt"];
    NSString *currentDateString;
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
    currentDateString = [dateFormat stringFromDate:[NSDate date]];
    NSDate *currentDate = [dateFormat dateFromString:currentDateString];
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *dayComponents = [gregorianCalendar components:NSDayCalendarUnit
                                                           fromDate:topicDate
                                                             toDate:currentDate
                                                            options:0];
    NSString *dayDifference = [NSString stringWithFormat:@"%@d", [@([dayComponents day]) stringValue]];
    NSString *fullName = [NSString stringWithFormat:@"%@ %@",[[homeTableData objectAtIndex:indexPath.row] valueForKey:@"userFirstName"],[[homeTableData objectAtIndex:indexPath.row] valueForKey:@"userLastName"]];
    NSString *pointCount = [[[homeTableData objectAtIndex:indexPath.row] valueForKey: @"nPoints"]stringValue];

    [followeeCell.title setText:[[homeTableData objectAtIndex:indexPath.row] valueForKey:@"title"]];
    [followeeCell.belief setText:[[homeTableData objectAtIndex:indexPath.row] valueForKey:@"voice"]];
    [followeeCell.profileName setText:fullName];
    [followeeCell.days setText:dayDifference];


    return followeeCell;}}

1 个答案:

答案 0 :(得分:0)

似乎在&#34;成功&#34;阻止您的网络呼叫,在解析响应并将其保存在核心数据中后,您不会调用[self.tableView reloadData]

deleteEntityData中调用reloadData(这就是你看到数据消失的原因)和fetchData,但fetchData最有可能在成功块完成之前执行,因此数据尚未保存在核心数据中。如果保存到核心数据后成功阻止,则调用[self.tableView reloadData,或者将调用移动到fetchData到成功块的末尾(也在保存核心数据上下文之后)