带谓词的ios Core数据错误

时间:2014-03-10 09:02:16

标签: ios objective-c core-data nspredicate

我的核心数据有一些奇怪的行为。

我有实体Card,其NSNumber属性idObject

当我想要更改此卡中的某些信息时,我会尝试在我的CoreData中找到类似的卡,但有时它会起作用,有时则不行。我的意思是下一个:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Card"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"idObject == %@", objectId];
request.predicate = predicate;
NSError *error;
NSArray *objects = [self.backgroundManagedObjectContext executeFetchRequest:request error:&error];

有时这段代码会返回对象数组,但有时会返回nil。我在上一部分代码之后添加了下一个代码:

request.predicate = nil;
NSArray *cards = [self.backgroundManagedObjectContext executeFetchRequest:request error:nil];

错误总是为零,所以一切都必须没问题。 cards数组的CardidObject一致,我试图找到它。最后,如果我们尝试多次执行下一个代码:

NSLog(@"idObject -%@-", objectId);
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Card"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"idObject == %@", objectId];
request.predicate = predicate;
NSError *error;
NSArray *objects = [self.backgroundManagedObjectContext executeFetchRequest:request error:&error];
NSLog(@"objects count = %i", objects.count);
request.predicate = nil;
NSArray *cards = [self.backgroundManagedObjectContext executeFetchRequest:request error:nil];
NSLog(@"\nCards:");
for (Card *card in cards) {
    NSLog(@"id -%@-", card.idObject);
}

所以我们有下一个结果。在第一次,您可以看到下一个:

2014-03-10 11:58:47.115[4397:6613] idObject -1-
2014-03-10 11:58:47.127[4397:6613] objects count = 1
2014-03-10 11:58:47.134[4397:6613] 
Cards:
2014-03-10 11:58:47.145[4397:6613] id -5-
2014-03-10 11:58:47.146[4397:6613] id -4-
2014-03-10 11:58:47.148[4397:6613] id -1-
2014-03-10 11:58:47.148[4397:6613] id -2-
2014-03-10 11:58:47.149[4397:6613] id -6-
2014-03-10 11:58:47.150[4397:6613] id -8-
2014-03-10 11:58:47.151[4397:6613] id -7-
2014-03-10 11:58:47.152[4397:6613] id -3-

第二个回复我:

2014-03-10 11:59:42.752[4397:9e2b] idObject -1-
2014-03-10 11:59:42.758[4397:9e2b] objects count = 0
2014-03-10 11:59:42.761[4397:9e2b] 
Cards:
2014-03-10 11:59:42.762[4397:9e2b] id -1-
2014-03-10 11:59:42.764[4397:9e2b] id -5-
2014-03-10 11:59:42.766[4397:9e2b] id -2-
2014-03-10 11:59:42.768[4397:9e2b] id -6-
2014-03-10 11:59:42.769[4397:9e2b] id -8-
2014-03-10 11:59:42.771[4397:9e2b] id -3-
2014-03-10 11:59:42.773[4397:9e2b] id -4-
2014-03-10 11:59:42.775[4397:9e2b] id -7-

所以我在cards数组中总是CardidObject,但是为什么我的谓词,它有时会返回我那张卡片,有时候没有?怎么了?

1 个答案:

答案 0 :(得分:2)

Card实体属性idObject的类型为NSNumber,将谓词中的idObject更改为NSNumber 即。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"idObject == %@", [NSNumber numberWithInt:[idObject integerValue]]];

或使用NSNumberFormatteridObject更改为NSNumber

希望这会对你有所帮助