Search code examples
objective-ccore-datanspredicatensfetchrequest

How Can I Get A Random String out of Core Data?


I've got a fetch request that uses NSPredicate to capture an array of NSString records from Core Data. However, the output seems to be unintelligible. I can't see what I'm missing. Here's the code:

NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entityQuote = [NSEntityDescription entityForName:@"Quotes" inManagedObjectContext:context];
NSFetchRequest *fetchRequestQuote = [[NSFetchRequest alloc] init];
[fetchRequestQuote setEntity:entityQuote];  

if ([sourceString isEqualToString:@"one"]) sourceString = @"  one";
if ([sourceString isEqualToString:@"two"]) sourceString = @"  two";
if ([sourceString isEqualToString:@"three"]) sourceString = @"  three";
if ([sourceString isEqualToString:@"four"]) sourceString = @"  four";
if ([sourceString isEqualToString:@"five"]) sourceString = @"  five";

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"quote contains %@", sourceString];
[fetchRequestQuote setPredicate:predicate];
NSArray *chosenSourceAll = [context executeFetchRequest:fetchRequestQuote error:nil];
int countSource = [chosenSourceAll count];
int rNumber = arc4random() % countSource;
NSLog(@"%d, %d, %@", rNumber, countSource, [chosenSourceAll objectAtIndex:rNumber]);

My output in console is:

2, 38, <NSManagedObject: 0x8c65860> (entity: Quotes; id: 0x7fc4790 <x-coredata://9FC73918-E9DC-4CDB-9D32-E640C9E24C71/Quotes/p3> ; data: <fault>)

Any thoughts on how I can get the string contents to output? Have I formatted my fetch request inappropriately? I did check the sqlite3 file and the strings are fine.


Solution

  • It looks like your Quotes class isn't an NSString at all, but rather a NSManagedObject. You probably defined some attribute on the Quotes object that is where you actually store your quote body. This is the attribute you want to access when you print to the log, not the object itself.

    If that's not right, post some more info about your Quotes class.