我正在尝试使用NSPredicate
来获取特定对象。问题是所有对象都被提取,它应该只是条件正确的特定对象。
- (void)fetchDevices {
// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
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: @"selectedRow == %@" , selectedRowNumber];
devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
[fetchRequest setPredicate:predicate];
}
selectedRowNumber
是int
文件中声明的.h
。
看看我的歌曲实体:
PS。如果需要更多信息,请在下方发表评论,我将提供。
答案 0 :(得分:3)
您必须在执行获取请求之前分配谓词。
另外,如果selectedRowNumber
是int
,那么您必须使用%d
格式
而不是%@
。
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"selectedRow == %d" , selectedRowNumber];
[fetchRequest setPredicate:predicate];
devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
答案 1 :(得分:0)
无需使用setEntity
设置实体。
[fetchRequest setPredicate:predicate]
只需设置谓词,就可以了。
- (void)fetchDevices {
// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Songs"];
// retrive the objects with a given value for a certain property
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"selectedRow == %@" , selectedRowNumber];
[fetchRequest setPredicate:predicate];
devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
[fetchRequest setPredicate:predicate];
}
答案 2 :(得分:0)
试试这个,
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"selectedRow = %@" , [NSNumber numberWithInt: selectedRowNumber]];
[fetchRequest setPredicate:predicate];
devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
答案 3 :(得分:0)
我认为您需要在[fetchRequest setPredicate:predicate];
之前放置devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
@"selectedRow == %d"
似乎也不对。您可能需要将其更改为@"selectedRow = %d"
无需再次设置实体。
所以代码可能看起来像这样。
- (void)fetchDevices {
int selectedRowNumber = 1;
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Songs"];
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"selectedRow = %d" , selectedRowNumber];
[fetchRequest setPredicate:predicate];
NSArray *devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
}
让我知道它是怎么回事:))