【发布时间】:2015-12-18 15:54:52
【问题描述】:
我正在尝试调整我用来从核心数据请求到对象数组中获取 id 字典的方法。但是,我对我想要的数组感到困惑。基本上,我想要一组具有所有适当属性的联系人。以下哪个联系人对象数组是我想要的,fetchedObject 还是 tmpArray?
-(NSMutableArray *) getContactsNeedingSync
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSManagedObjectContext *context = [IDModel sharedInstance].managedObjectContext;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"needsync==@1"];
fetchRequest.predicate = predicate;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Contacts" inManagedObjectContext:context];
fetchRequest.entity = entity;
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"cid" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
fetchRequest.sortDescriptors = sortDescriptors;
NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
NSError *error = nil;
if (![fetchedResultsController performFetch:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
NSArray *fetchedObjects = fetchedResultsController.fetchedObjects;
//is this the array I want?
NSInteger resultCount = [fetchedObjects count];
if (resultCount == 0) {
NSLog(@"result Count is zero");
return [NSMutableArray array];//nothing in the Core Data store
}
else {
Contacts *contact;
NSMutableArray *tmpArray = [NSMutableArray array];
int i;
for (i = 0; i < resultCount; i++) {
contact = fetchedObjects[i];
tmpArray[contact.cid] = contact;
}
return tmpArray;//is this array I want?
}
context = nil;
}
【问题讨论】:
-
你为什么有
tmpArray?你为什么使用NSFetchedResultsController? -
好问题。改编自代码以获取 id 字典...我应该只使用 nsfetch 吗? fetchedObjects 是我需要的一切吗?第二部分可能是多余的。
标签: ios objective-c core-data nsfetchedresultscontroller