Ios 在创建新实体之前删除CoreData实体无效

Ios 在创建新实体之前删除CoreData实体无效,ios,core-data,Ios,Core Data,基本上,我试图在调用web服务收集最新数据(因为数据将经常从多个平台更新)之前,在加载视图时清除CoreData实体。但是,当我实现删除实体代码时,表视图中不会显示任何数据。我检查了代码在我的视图中何时被触发,并且它似乎被正确地调用 2014-04-09 21:13:21.113 Karmo[28531:60b] Delete code being called 2014-04-09 21:13:21.122 Karmo[28531:60b] SetUpData being called 201

基本上,我试图在调用web服务收集最新数据(因为数据将经常从多个平台更新)之前,在加载视图时清除CoreData实体。但是,当我实现删除实体代码时,表视图中不会显示任何数据。我检查了代码在我的视图中何时被触发,并且它似乎被正确地调用

2014-04-09 21:13:21.113 Karmo[28531:60b] Delete code being called
2014-04-09 21:13:21.122 Karmo[28531:60b] SetUpData being called
2014-04-09 21:13:21.123 Karmo[28531:60b] FetchData being called
如果我注释掉删除代码,所有数据都会显示出来(但它会被复制,因为在获取新数据之前旧数据不会被删除:)。我觉得我可能错过了一些小东西。任何帮助都将不胜感激。下面我介绍了viewDidLoad、delete、setUp和fetch代码

- (void)viewDidLoad {

  [super viewDidLoad];

  //Delete entities from Core Data
  [self deleteEntityData];

  //Call the API and store the data to Core Data
  [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:@"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]);
    };

}

}




- (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=XXXX" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

//Code to set up new Core Data Entity 

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


    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];


}
-(void)viewDidLoad{
[超级视图下载];
//从核心数据中删除实体
[自删除实体数据];
//调用API并将数据存储到核心数据
[自设置数据];}
-(void)deleteEntityData{
//删除核心数据中所有旧的Exlpore视图实体
NSLog(@“删除正在调用的代码”);
NSManagedObjectContext*上下文=[self-managedObjectContext];
NSFetchRequest*fetch=[[NSFetchRequest alloc]init];
[fetch setEntity:[NSEntityDescription entityForName:@“ExploreView”inManagedObjectContext:context]];
[获取集合IncludePropertyValue:否];
n错误*错误=nil;
NSArray*entities=[context executeFetchRequest:获取错误:&error];
对于(NSManagedObject*实体中的exploreView){
[上下文删除对象:exploreView];
如果(![上下文保存:&错误]){
NSLog(@“无法保存!%@%@),错误,[错误本地化描述];
};
}
}
-(无效)设置数据{
//在此处为get请求创建带有用户ID的字符串
NSLog(@“正在调用的设置数据”);
//使用Dribble API基本URL初始化AFHTTPRequestOperationManager
_operationManager=[[AFHTTPRequestOperationManager alloc]initWithBaseURL:[NSURL URLWithString:@]http://www.karmo.com/explore/index"]];
[\u operationManager GET:@”?用户id=XXXX“参数:无成功:^(AFHTTPRequestOperation*操作,id响应对象){
//用于设置新核心数据实体的代码
}失败:^(AFHTTPRequestOperation*操作,NSError*错误){
NSLog(@“无法从Karmo API获取快照!”);
UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@“无法连接”
消息:@“我们无法连接到karmo数据库。某些数据可能已过期。”
代表:赛尔夫
取消按钮:@“确定”
其他按钮:无];
[警报显示];
} ];
[自取数据];}
-(void)获取数据{
NSLog(@“正在调用的获取数据”);
[exploreSortData removeAllObjects];
[exploreTableData removeAllObjects];
self.timeSortButton.backgroundColor=[UIColor clearColor];
self.voteSortButton.backgroundColor=[UIColor lightGrayColor];
NSMUTABLEARRY*子预测=[[NSMUTABLEARRY alloc]init];
//从持久数据存储中获取配方
NSManagedObjectContext*managedObjectContext=[self-managedObjectContext];
NSFetchRequest*fetchRequest=[[NSFetchRequest alloc]initWithEntityName:@“ExploreView”];
exploreSortData=[[managedObjectContext executeFetchRequest:fetchRequest错误:nil]mutableCopy];
//可能需要在此处调用类别slelctions。使用if语句捕获,以便在选择非时显示所有类别
如果([selectedCategoriesFilter count]>0){
对于(int i=0;i<[selectedCategoriesFilter count];i++){
NSPredicate*newPredicate=[NSPredicate predicateWithFormat:@“category==[c]%@”,[[selectedCategoriesFilter objectAtIndex:i]valueForKey:@“categorySelected”];
[子预测addObject:newPredicate];
}
NSPredicate*combinedPredicate=[NSCompoundPredicate或PredicateWithSubPredicates:subPredicates];
NSArray*filterData=[[NSArray alloc]init];
filterData=[exploreSortData FilteredArrayingPredicate:combinedPredicate];
NSSortDescriptor*VotedDescriptor=[NSSortDescriptor SortDescriptor WithKey:@“TotalVoces”升序:否];
NSMutableArray*描述符=[[NSArray arrayWithObjects:VotedDescriptor,nil]mutableCopy];
exploreTableData=[[filterData SorterDarrayusingDescriptors:descriptors]mutableCopy];
[self.tableView重载数据];
}否则{
NSSortDescriptor*VotedDescriptor=[NSSortDescriptor SortDescriptor WithKey:@“TotalVoces”升序:否];
NSMutableArray*描述符=[[NSArray arrayWithObjects:VotedDescriptor,nil]mutableCopy];
exploreTableData=[[exploreSortData sortedarrayingdescriptors:descriptors]mutableCopy];
[self.tableView重载数据];
}

}

我认为在从服务器删除或更新数据后,您需要调用
[self.tableView reloadData]
。所以您可能错过了重新加载数据的调用


不相关,但我在代码中注意到的另一件事是,您正在for循环中调用
[context save:&error]
。您应该将其移出for循环以提高性能。单个[context save]将保存您在for循环中进行的所有删除。

请注意区别-删除CoreData实体不会立即释放与它们关联的NSManagedObjects

您的代码可能会保留您刚刚在某处删除的实体(在数组或字典中,或者只是作为某个类的成员),因此,您的tableView仍然“看到”这些对象


通常,为了避免此类问题,您使用为“实体”(vs.“类”)配置的NSArrayController,并将tableView绑定到该阵列控制器。ArrayController针对的是实体,而不是它们的对象表示,因此当您删除或添加实体时,它将保持同步。

我在删除数据后添加了
[self.tableView reloadData]
调用,但仍然得到相同的结果(空白tableView)。谢谢你的帮助