【问题标题】:Predicate fetch all objects谓词获取所有对象
【发布时间】:2014-01-14 19:13:55
【问题描述】:

我正在尝试制作一个 NSPredicate 来获取特定对象。问题是 NSPredicate 获取所有对象而不是仅获取特定对象。我做错了什么?

我的代码如下所示:

- (void)fetchDevices {
    // Fetch the devices from persistent data store

    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Songs"];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Songs" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];
    // retrive the objects with a given value for a certain property
    NSPredicate *predicate = [NSPredicate predicateWithFormat: @"%d == %d", currentRow,      [device valueForKey:@"selectedRow"]];

    [fetchRequest setPredicate:predicate];

}

属性和变量:

@property (strong) NSMutableArray *devices;
currentRow = indexPath.row;
[device valueForKey:@"selectedRow"] 

[device valueForKey:@"selectedRow"](这是一个存储在我的核心数据实体中的 INT)

【问题讨论】:

  • 在您的谓词格式中,您希望指定一个属性名称,例如NSPredicate *predicate = [NSPredicate predicateWithFormat:@"songName == %@', name]
  • 正如@BlackRider 所示,谓词的左侧应该是您要过滤的 Song 实体上的属性名称。属性名称是什么?
  • 属性为 selectedRow。那应该是这样吗? (NSPredicate *predicate = [NSPredicate predicateWithFormat:@"selectedRow == %@', name, currentrow])??

标签: ios objective-c core-data nspredicate


【解决方案1】:

很难从您的问题中看出,因为不清楚 Songs 实体上存在哪些属性或您希望如何匹配它们。然而,这个谓词的主要问题是:

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"%d == %d", currentRow,      [device valueForKey:@"selectedRow"]];

...是它不尝试匹配Songs实体上的任何东西。谓词字符串需要包含您要获取的实体类型的属性名称之一。或者,如果您在局部变量中有属性名称(也许这就是[device valueForKey:@"selectedRow"] 的含义?)您需要在谓词中使用%K。你所拥有的是一个两边都是整数值的谓词,我保证属性 name 不是整数。

再一次,如果没有更好地解释您正在尝试做什么,我无法告诉您您的谓词应该是什么。但格式字符串的左侧确实需要文字属性名称或匹配属性名称的%K 才能有效过滤。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    相关资源
    最近更新 更多