1

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

1 Answers1

0

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;
pbasdf
  • 21,386
  • 4
  • 43
  • 75
  • What should I do with "firstObject"? Getting an error there. – user3638160 Sep 03 '15 at 19:33
  • @user3638160 I've amended the code to use a local NSArray to hold the results of the fetch. I think this should work. Out of interest, what class is `self.template`? – pbasdf Sep 03 '15 at 19:45
  • That works amazing! But now I have another (small) problem. I want to fetch the latest. When I update or make a new object it fetches the first ever made. How could I change this? – user3638160 Sep 03 '15 at 19:53
  • Change `firstObject` to `lastObject`. – pbasdf Sep 03 '15 at 19:54
  • A big thanks! You've made my day :). Pretty dumb of myself that I didn't saw that last minor problem :P – user3638160 Sep 03 '15 at 19:56