I working on an app using core data. The greatest part of the implementation worked out well but at the very very very last moment I get an NSException error. I can fetch the core data and put them in a string, but I can't put it in a textView, label or whatever.
This is the code for the fetch.
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Template"];
self.template = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSLog(@"%@ viewDidLoad", [template valueForKey:@"name"]);
self.nameStringString = [template valueForKey:@"name"];
NSLog(@"%@ viewDidLoad String", self.nameStringString);
self.testLabel.text = self.nameStringString;
I tested at a few moments in the code wether the data was still intact or it was missing. The code up here works fine until the last sentence. What should I do?
Thank you in advance!
Edit: Here is the error I get. After the error the app will be terminated. 2015-09-03 21:20:54.511 ****[1640:671115] -[__NSArray0 rangeOfCharacterFromSet:]: unrecognized selector sent to instance 0x1255022a0
The executeFetchRequest
returns an NSArray, even if there is only one object to fetch. You need to extract the individual members of the array before obtaining the valueForKey
:
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Template"];
NSArray *templateArray = [managedObjectContext executeFetchRequest:fetchRequest error:nil];
NSManagedObject *firstTemplate = [templateArray firstObject];
self.nameStringString = [firstTemplate valueForKey:@"name"];
NSLog(@"%@ viewDidLoad String", self.nameStringString);
self.testLabel.text = self.nameStringString;