我正在使用UICollectionView和Core Data。
我似乎无法弄清楚为什么我无法从Core Data中删除对象。它在[self.managedObjectContext deleteObject:animation];
崩溃时出现index 0 beyond bounds for empty array
错误。以下方法是从另一个viewcontroller调用的委托方法。它获取时间戳NSInteger并应创建具有该时间戳的NSPredicate。
奇怪的是,当我采用animationTimestamp NSInteger并将其硬编码为:
[NSPredicate predicateWithFormat:@"timestamp == %i", @"1370169109"]
它有效,对象被删除而没有错误。但是,当我想将参数作为参数传递时,它会崩溃。我试过把它变成一个字符串,NSNumber等。当我拿参数时,什么都没有用,它只在我硬编码时才有效。我已经记录了animationTimestamp,它显示了正确的值,所以我卡住了。
谢谢!
- (void)deleteAnimationWithTimestamp:(NSInteger)animationTimestamp {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Animations" inManagedObjectContext:self.managedObjectContext];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"timestamp == %i", animationTimestamp];
[fetchRequest setPredicate:predicate];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *animations = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *animation in animations) {
[self.managedObjectContext deleteObject:animation];
}
// Save core data
if (![self.managedObjectContext save:&error]) {
NSLog(@"Couldn't save: %@", [error localizedDescription]);
}
[self.animationsCollectionView reloadData];
}
编辑: 更多信息可能很重要。模型中的timestamp属性是64位整数(顺便说一句,它应该是什么?)。当我创建我使用的对象时:
NSNumber *timestampNumber = [NSNumber numberWithInt:timestamp];
[newAnimation setValue:timestampNumber forKey:@"timestamp"];
答案 0 :(得分:0)
从NSNumber获取NSInteger值 喜欢
NSInteger timestampNumber = [[NSNumber numberWithInt:timestamp] integerValue];
// then use this integer
[newAnimation setValue:timestampNumber forKey:@"timestamp"];
// or in
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"timestamp == %d", timestampNumber];