0
votes

I have completed and reproduced Core Data tutorials using a tableview to display contents. However, I want to access an Entity through a fetch on a view without a tableview. I used the following fetch code, but the count returned is always 0. The data exists when the database is opened using SQLite tools.

    NSManagedObject *entryObj;
XYZDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Quote" inManagedObjectContext:managedObjectContext]; 
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"id" ascending:YES];  
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];   

[request setSortDescriptors:sortDescriptors];
[request setEntity: entity]; 

NSArray *results = [managedObjectContext executeFetchRequest:request error:nil];

if (results == nil) {
    NSLog(@"No results found");
    entryObj = nil;
}else {
    NSLog(@"results %d", [results count]);
}

[request release];
[sortDescriptors release];  

count returned is always 0; it should be 5.

Can anyone point me to a reference or tutorial regarding creating a controller not to be used with a tableview.

1

1 Answers

1
votes

As far as I can tell, everything looks fine (except I'm a little worried about using 'id' as an attribute name, since it's a keyword in Objective-C). Try removing the sort descriptor and see if that changes anything. Also, add an error check. Perhaps something is happening that that can tell you. And I assume "Quote" is the right name for the entity. If none of that helps, I don't think the problem is in the fetch request.

For what it's worth, here's how I would write it:

XYZDelegate * appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext * context = appDelegate.managedObjectContext;

NSFetchRequest * request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Quote" inManagedObjectContext:context];
NSSortDescriptor * sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"id" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
[request setEntity:[NSEntityDescription entityForName:@"Quote" inManagedObjectContext:context]];
NSError * error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
[request release];

if (error) {
    NSLog(@"ERROR: %@ %@", [error localizedDescription], [error userInfo]);
}

if (results == nil) {
    NSLog(@"No results found");
    entryObj = nil;
}
else {
    NSLog(@"results %d", [results count]);
}