我正在使用CoreData从Web服务中提取数据,然后将其放入tableview。当视图首次加载时,数据会出现在tableview中,但在一瞬间它会全部消失。它可能与删除代码(我在上传新数据之前用于清除CoreData实体)有关,因为没有该代码,tableview可以工作。我已经包含了我用来设置数据的所有代码,将其加载到表视图中,删除它并重新加载它。
代码可以在下面找到...任何帮助表示赞赏。谢谢。
- (void)viewDidLoad {
[super viewDidLoad];
[self findSelectedCategories];
[self setUpData];
}
- (void) findSelectedCategories {
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"ExploreCat"];
selectedCategoriesFilter = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
}
- (void) deleteEntityData {
NSLog(@"Delete code being called");
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
[fetch setEntity:[NSEntityDescription entityForName:@"ExploreView" 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 {
//Create the string with the userID for the get request here
NSLog(@"SetUpData being called");
//Initialize AFHTTPRequestOperationManager with Dribbble API base URL
_operationManager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.karmo.com/explore/index"]];
[_operationManager GET:@"?user_id=5332bb35c9f9550b008ed49c" 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
for (int i = 0; i < [[responseObject valueForKey:@"belief"] count]; i++) {
NSString * topicID = [[[[responseObject valueForKey:@"belief"] valueForKey:@"topic"] objectAtIndex:i] valueForKey:@"_id"];
NSString * title = [[[[responseObject valueForKey:@"belief"] valueForKey:@"topic"] objectAtIndex:i] valueForKey:@"title"];
NSString *body = [[[[responseObject valueForKey:@"belief"] valueForKey:@"topic"] objectAtIndex:i] valueForKey:@"body"];
NSString * category = [[[[responseObject valueForKey:@"belief"] valueForKey:@"topic"] objectAtIndex:i] valueForKey:@"category"];
NSNumber * nFor = @([[[[[responseObject valueForKey:@"belief"] valueForKey:@"topic"] objectAtIndex:i] valueForKey:@"nFor"] intValue]);
NSNumber * nAgainst = @([[[[[responseObject valueForKey:@"belief"] valueForKey:@"topic"] objectAtIndex:i] valueForKey:@"nAgainst"] intValue]);
NSNumber *totalVotes = @([nFor integerValue] + [nAgainst integerValue]);
NSString * vote = [[[responseObject valueForKey:@"belief"] objectAtIndex:i] valueForKey:@"vote"];
NSString *beliefID = [[[responseObject valueForKey:@"belief"] objectAtIndex:i] valueForKey:@"_id"];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *createdAt = [dateFormat dateFromString:[[[[responseObject valueForKey:@"belief"] valueForKey:@"topic"] objectAtIndex:i] valueForKey:@"createdAt"]];
NSDate *updatedAt = [dateFormat dateFromString:[[[[responseObject valueForKey:@"belief"] valueForKey:@"topic"] objectAtIndex:i] valueForKey:@"updatedAt"]];
NSManagedObjectContext *context = [self managedObjectContext];
// Create a new managed object
NSManagedObject *newExplore = [NSEntityDescription insertNewObjectForEntityForName:@"ExploreView"
inManagedObjectContext:context];
[newExplore setValue:topicID forKey:@"topicID"];
[newExplore setValue:title forKey:@"title"];
[newExplore setValue:body forKey:@"body"];
[newExplore setValue:category forKey:@"category"];
[newExplore setValue:nFor forKey:@"nFor"];
[newExplore setValue:nAgainst forKey:@"nAgainst"];
[newExplore setValue:vote forKey:@"vote"];
[newExplore setValue:totalVotes forKey:@"totalVotes"];
[newExplore setValue:beliefID forKey:@"beliefID"];
[newExplore setValue:createdAt forKey:@"createdAt"];
[newExplore setValue:updatedAt forKey:@"updatedAt"];
// Save the object to persistent store
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
}
for (int i = 0; i < [[responseObject valueForKey:@"topic"] count]; i++) {
NSString * topicID = [[[responseObject valueForKey:@"topic"] objectAtIndex:i] valueForKey:@"_id"];
NSString * title = [[[responseObject valueForKey:@"topic"] objectAtIndex:i] valueForKey:@"title"];
NSString *body = [[[responseObject valueForKey:@"topic"] objectAtIndex:i] valueForKey:@"body"];
NSString * category = [[[responseObject valueForKey:@"topic"] objectAtIndex:i] valueForKey:@"category"];
NSNumber * nAgainst = @([[[[responseObject valueForKey:@"topic"] objectAtIndex:i] valueForKey:@"nAgainst"] intValue]);
NSNumber * nFor = @([[[[responseObject valueForKey:@"topic"] objectAtIndex:i] valueForKey:@"nFor"] intValue]);
NSNumber *totalVotes = @([nFor integerValue] + [nAgainst integerValue]);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *createdAt = [dateFormat dateFromString:[[[responseObject valueForKey:@"topic"] objectAtIndex:i] valueForKey:@"createdAt"]];
NSManagedObjectContext *context = [self managedObjectContext];
// Create a new managed object
NSManagedObject *newExplore = [NSEntityDescription insertNewObjectForEntityForName:@"ExploreView"
inManagedObjectContext:context];
[newExplore setValue:topicID forKey:@"topicID"];
[newExplore setValue:title forKey:@"title"];
[newExplore setValue:body forKey:@"body"];
[newExplore setValue:category forKey:@"category"];
[newExplore setValue:nFor forKey:@"nFor"];
[newExplore setValue:nAgainst forKey:@"nAgainst"];
[newExplore setValue:totalVotes forKey:@"totalVotes"];
[newExplore setValue:createdAt forKey:@"createdAt"];
NSError *error = nil;
// Save the object to persistent store
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 {
NSLog(@"FetchData being called");
[exploreSortData removeAllObjects];
[exploreTableData removeAllObjects];
self.timeSortButton.backgroundColor = [UIColor clearColor];
self.voteSortButton.backgroundColor = [UIColor lightGrayColor];
NSMutableArray *subPredicates = [[NSMutableArray alloc] init];
// Fetch the recipes from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"ExploreView"];
exploreSortData = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
//Would probably need to call the category slelctions here. Use an if statment to capture so if non are seletced that all the categories are displayed
if ([selectedCategoriesFilter count] > 0 ) {
for (int i = 0; i < [selectedCategoriesFilter count]; i++) {
NSPredicate *newPredicate = [NSPredicate predicateWithFormat:@"category ==[c] %@",[[selectedCategoriesFilter objectAtIndex:i]valueForKey:@"categorySelected"]];
[subPredicates addObject:newPredicate];
}
NSPredicate *combinedPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates];
NSArray *filterData = [[NSArray alloc]init];
filterData = [exploreSortData filteredArrayUsingPredicate:combinedPredicate];
NSSortDescriptor *voteDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"totalVotes" ascending:NO];
NSMutableArray * descriptors = [[NSArray arrayWithObjects:voteDescriptor, nil]mutableCopy];
exploreTableData = [[filterData sortedArrayUsingDescriptors:descriptors]mutableCopy];
[self.tableView reloadData];
} else {
NSSortDescriptor *voteDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"totalVotes" ascending:NO];
NSMutableArray * descriptors = [[NSArray arrayWithObjects:voteDescriptor, nil]mutableCopy];
exploreTableData = [[exploreSortData sortedArrayUsingDescriptors:descriptors]mutableCopy];
[self.tableView reloadData];
}}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[[exploreTableData objectAtIndex:indexPath.row] valueForKey:@"beliefID"] isEqualToString:@"0"]) {
ExploreVoteCell *cell = (ExploreVoteCell *) [tableView dequeueReusableCellWithIdentifier:@"ExploreVote" forIndexPath:indexPath];
NSDate * topicDate = [[exploreTableData objectAtIndex:indexPath.row] valueForKey:@"createdAt"];
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 *voteCount = [[[exploreTableData objectAtIndex:indexPath.row] valueForKey: @"totalVotes"]stringValue];
[cell.topicTitle setText:[[exploreTableData objectAtIndex:indexPath.row] valueForKey:@"title"]];
[cell.votesCount setText:voteCount];
[cell.timeDayCount setText:dayDifference];
return cell;
} else {
ExploreBeliefCell *cell = (ExploreBeliefCell *) [tableView dequeueReusableCellWithIdentifier:@"ExploreBelief" forIndexPath:indexPath];
UISwipeGestureRecognizer *gesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRightChangeVote:)];
gesture.direction = UISwipeGestureRecognizerDirectionRight;
[cell addGestureRecognizer:gesture];
[cell.topicTitle setText:[[exploreTableData objectAtIndex:indexPath.row] valueForKey:@"title"]];
return cell;
}}
答案 0 :(得分:0)
我的第一个猜测是你的保存电话不会以某种方式同步。尝试将deleteEntityData
方法添加到将触发剩余过程的完成块。
您可以使用 -
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(modalDidChange:) name:NSManagedObjectContextObjectsDidChangeNotification object:yourManagedObjectContext];
然后实施 -
- (void)modalDidChange:(NSNotification *)note
{
NSSet *updatedObjects = [[note userInfo] objectForKey:NSUpdatedObjectsKey];
NSSet *deletedObjects = [[note userInfo] objectForKey:NSDeletedObjectsKey];
NSSet *insertedObjects = [[note userInfo] objectForKey:NSInsertedObjectsKey];
}
跟踪您的上下文中发生的事情。