【问题标题】:Number of core data objects with a defined attribute value具有已定义属性值的核心数据对象的数量
【发布时间】:2014-02-17 03:25:53
【问题描述】:

我正在使用以下获取请求来删除核心数据对象:

NSEntityDescription *entity=[NSEntityDescription entityForName:@"entityName" inManagedObjectContext:context];
  NSFetchRequest *fetch=[[NSFetchRequest alloc] init];
  [fetch setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(value1 == %@) AND (value2 == %@)", data1, data2];
 [fetch setPredicate:predicate];
  //... add sorts if you want them
  NSError *fetchError;
  NSArray *fetchedData=[self.moc executeFetchRequest:fetch error:&fetchError];
 for (NSManagedObject *product in fetchedProducts) {
    [context deleteObject:product];
  }

我需要的是仅当核心数据实体中[value1 isEqualToString: @"borrar"] 的对象数大于1 时才执行获取请求。如何添加此条件?

***编辑 属性value1 是一个临时属性。

【问题讨论】:

  • “borrar”是谓词中已使用的值data1data2 之一吗?
  • 是的,它是值之一,但如果 countForFetchRequest 计算对象的数量,我可以更改谓词并仅考虑 data2。
  • 所以你想删除所有具有 value1 == "borrar" 和 value == "someOtherString" 的对象,但只有如果至少有两个对象具有 value1 == “博拉尔”?
  • 正是,这正是我所需要的。
  • 不能在核心数据获取请求中使用瞬态属性。我已经相应地更新了答案。

标签: ios core-data


【解决方案1】:
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"(Value1 == borrar)"];
[fetch setPredicate:predicate];
NSError *fetchError;
NSArray *fetchedData=[self.moc executeFetchRequest:fetch error:&fetchError];
for(int i=0;i<fechedData.count;i++){
     [context deleteObject:[fechedData objectAtIndex:i]valueForKey:@"Value1"];
}

【讨论】:

  • 谢谢你的提议。但我猜你没有考虑到我问题的主要条件。在删除对象之前,您在哪里考虑对象的数量是否大于 1?对不起,如果我错了...
  • if([fechedData count]>0){//for循环语句(上)}
  • 谢谢,我也会检查你的建议。
【解决方案2】:

要检查有多少个具有给定属性值的对象,请使用countForFetchRequest:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"entityName"];
[request setPredicate:[NSPredicate predicateWithFormat:@"value1 = %@", @"borrar"]];
NSError *error;
NSUInteger count = [self.moc countForFetchRequest:request error:&error];
if (count == NSNotFound) {
    // some error occurred
} else if (count > 1) {
    // more the one object with "value1 == borrar"
} 

更新(根据编辑的问题):你不能使用瞬态属性 在核心数据获取请求中。如果“value1”是瞬态属性,则只能 获取所有具有“value2 == something”的对象,然后遍历获取的对象 数组来检查是否有多个具有“value1 == borrar”的对象。

【讨论】:

  • 谢谢你,Martin,我会检查你的提议,我想你一如既往的正确。谢谢你的责任。
  • 但是条件很重要。就表格视图而言,我需要的是从一个部分中删除一行(将对象分类为部分的瞬态属性),仅当该部分中有多个对象时。换句话说,每个部分都有一个特殊行,如果该部分中有更多行,则应删除该行。要删除的行有一个 value2 属性,该属性不同于其部分的正常行的 value2 属性。
  • 明白了,但是您建议在代码中的哪个位置放置这个获取请求?
  • @mvasco:要检查一个部分中有多少行,您可以直接调用NSInteger count = [self.tableView numberOfRowsInSection:section],这可能会有所帮助。 - 否则,您可能应该使用有关您实际尝试实现的目标的更多信息来更新您的问题。
  • 然后,为了询问第 0 节中有多少行,我可以调用 NSInteger rowsInSection0 = [self.tableView numberOfRowsInSection:0] 但它不起作用......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-17
相关资源
最近更新 更多