2013-06-02 32 views
0

我正在使用UICollectionView以及核心数据。核心数据:deleteObject崩溃应用程序,NSPredicate的原因是什么?

我似乎无法弄清楚为什么我无法从核心数据中删除一个对象。它崩溃在[self.managedObjectContext deleteObject:animation];index 0 beyond bounds for empty array错误。以下方法是从另一个视图控制器调用的委托方法。它得到一个时间戳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

请问您的对象有关系依赖于任何其他实体? – kushyar

+0

尝试在您的谓词中将%i更改为%d –

+0

@kushyar我只有一个实体动画。 –

回答

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];