从核心数据中获取对象数组

时间:2015-12-18 15:54:52

标签: ios objective-c core-data nsfetchedresultscontroller

我正在尝试调整我正在使用的方法来获取从核心数据请求到对象数组的ID字典。但是,我对我想要的数组感到困惑。基本上,我想要一系列具有所有适当属性的联系人。以下哪个联系人对象是我想要的,fetchedObjecttmpArray

-(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;
}

1 个答案:

答案 0 :(得分:2)

您的代码会创建一个获取请求并将其设置为收集一组已排序的对象。然后使用NSFetchedResultsController收集获取请求的结果。然后,您将获得一些代码来解析排序数据(init tmpArray)。

您可以通过删除NSFetchedResultsController并直接执行提取请求来简化此操作。 NSFetchedResultsController没有帮助您,因为您没有向其添加代理或保留代理。

由于NSSortDescriptor,数据也已经排序。实际上,如果你不是因为你试图插入一个不够大的数组而导致崩溃......那么,删除tmpArray和相关的代码。