ios Core Data删除第n个对象

时间:2014-02-28 13:52:16

标签: core-data ios7

我有一个简单的iOS7 CoreData应用程序,只有一个实体。 该实体仅应存储最后100条记录。 当我添加第101条记录时 - 我想删除最旧的记录,以便始终保留100条(或更少)记录

如何删除“第n条记录”?

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

  NSError *error;

//clear job: delete the old records before inserting new ones
NSFetchRequest *del_fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
[del_fetchRequest setEntity: [NSEntityDescription entityForName:@"News" inManagedObjectContext:_context]];


[del_fetchRequest setPredicate: [NSPredicate predicateWithFormat: @"(RecordID< %@)", number_here]];


NSArray *del_newsMatchingTitle = [_context executeFetchRequest:del_fetchRequest error:&error];

for (NSManagedObject *managedObject in del_newsMatchingTitle) {
    [_context deleteObject:managedObject];
    //NSLog(@"%@ object deleted",managedObject);
}
if (![_context save:&error]) {
    // NSLog(@"Error deleting %@ - error:%@",del_fetchRequest,error);
}