1

我有以下代码当前清除我的 NSManagedObjectContext 中的所有对象:

- (void)clearObjectList:(NSString *)identifier
{
    // TODO: Delete any entries with the identifier at the start of the object's name
    NSLog(@"Clearing the URL list...");

    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    NSFetchRequest * fetch = [[NSFetchRequest alloc] init];
    [fetch setEntity:[NSEntityDescription entityForName:@"URL" inManagedObjectContext:context]];
    NSArray * result = [context executeFetchRequest:fetch error:nil];
    for (id basket in result)
    {
        // Code here to check if we should delete this object
        [context deleteObject:basket];
    }

    NSError *error = nil;
    if (![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        //abort();
    }
}

我对 URL 的数据模型是:

dateAccessed: Date
        name: String
         url: String

我想访问 objects 键name以确定是否应该将其删除。我如何访问这个?

4

2 回答 2

2

尝试这个:

for(URL *basket in result)
{
    if([basket.name isEqualToString:identifier])
        [context deleteObject:basket];
}
于 2012-05-31T20:08:37.883 回答
1

循环遍历结果时,您知道您将得到的只是NSManagedObjects。或者,如果你已经创建了 NSManagedObject 子类,你将只能得到URL对象。因此,您可以替换idNSManagedObject *URL *在您的 for 循环中。

如果您确实创建了我建议的子类,您可以访问namewith dot notation: basket.name。如果你没有,你可以通过调用来访问它[basket valueForKey:@"name"]

于 2012-05-31T20:06:49.023 回答