Reputation: 4764
I am trying to adapt a method I was using to get a dictionary of ids from a core data request to an array of objects. However, I am getting confused about what array is the one I want. Basically, I want an array of contacts with all the appropriate attributes. Which array of contact objects in the following is the one I want, the fetchedObject
or the 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;
}
Upvotes: 1
Views: 648
Reputation: 119031
Your code creates a fetch request and sets it up to collect a sorted set of objects. You then use an NSFetchedResultsController
to collect the results for the fetch request. You then have a bit of code which resorts the sorted data (init tmpArray
).
You can simplify this by removing the NSFetchedResultsController
and just executing the fetch request directly. The NSFetchedResultsController
isn't helping you as you aren't adding a delegate to it or retaining it.
The data is also already sorted because of the NSSortDescriptor
. Indeed, if it was't you'd get crashes as you'd be trying to insert into an array that wasn't big enough... So, remove tmpArray
and the associated code.
Upvotes: 2