开发者

Fetch Data using predicate. Retrieve single value

I want to retrieve a single value (String) from "Entry." I believe I am missing something. Can someone point it out?

XYZAppDelegate *appDelegate = [[UIApplication sharedApplicatio开发者_JS百科n] delegate];

NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", entryToSearchFor]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entry" inManagedObjectContext:managedObjectContext]; 
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO]; 
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];   

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

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

if (results == nil) {
    NSLog(@"No results found");     
}else {
    NSLog(@"entryToSearchFor %@", entryToSearchFor);
    NSLog(@"results %@", [results objectAtIndex:0]);

}

Btw, the NSLog results outputs the following:

results <NSManagedObject: 0x3d2d360> (entity: Entry; id: 0x3d13650 <x-coredata://6EA12ADA-8C0B-477F-801C-B44FE6E6C91C/Entry/p3> ; data: <fault>)


NSFetchRequest will return an array of NSManagedObjects that matches the request. That is consistent with what you are seeing. Assuming you want to fetch the name, you can do NSLog(@"the name is %@", [[results objectAtIndex:0] name]); to print out the name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜