我有以下代码,目前清除我的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
我想访问对象键name
以确定是否应将其删除。我该如何访问?
答案 0 :(得分:2)
试试这个:
for(URL *basket in result)
{
if([basket.name isEqualToString:identifier])
[context deleteObject:basket];
}
答案 1 :(得分:1)
在循环搜索结果时,您知道您将获得的所有内容都是NSManagedObject
。或者,如果您已创建NSManagedObject子类,则只会返回URL
个对象。因此,您可以在for循环中将id
替换为NSManagedObject *
或URL *
。
如果您确实创建了我建议的子类,则可以使用点表示法name
访问basket.name
。如果您没有,可以通过拨打[basket valueForKey:@"name"]
来访问它。