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

我有实体 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 数组中总是 Card 和这样的 idObject ,但为什么我的谓词,它有时会返回我那张卡片,有时不会?怎么了?

最佳答案

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

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

或使用 NSNumberFormatteridObject 更改为 NSNumber

希望能帮到你

关于带有谓词的ios核心数据错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22295831/

10-12 02:31