问题
I'm trying to retrieve an attribute from my core data model and put the acquired string into the title of my navigation bar. I must be doing something wrong, as I cannot set my retrieved string as the title, yet I can set the title if I manually enter the string.
Here is how I am retrieving from Core Data:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Area" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
//set predicate
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"identifier == %@", self.area_id];
NSArray *area = [context executeFetchRequest:fetchRequest error:&error];
NSString *area_name = [area valueForKey:@"name"];
NSString *test = @"test";
NSLog(@"%@",test);
NSLog(@"%@",area_name);
When I set the title using self.tabBarController.title = area_name; I get "NSArrayI stringByTrimmingCharactersInSet:]: unrecognized selector sent to instance" and it sets just fine when I set it to the test variable.
I also noticed that the NSLog for the variable test is "test" whereas the NSLog output for area_name is: ( "Single Area" )
Is this because of how I am retrieving my area_name from the array? Should I be using a dictionary instead? Forgive me for my ignorance, I'm fairly new to obj-c.
Thanks.
回答1:
Here is mistake
NSString *area_name = [area valueForKey:@"name"];
area
object is type of NSArray
which contains Area
objects.
So you need to get element from that array, and then read name
.
Area *firstArea = [area firstObject];
NSString *area_name = firstArea.name;
NSLog(@"%@",area_name);
回答2:
Change the predicate to this:
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"identifier = %@", self.area_id];
I suppose than self.area_id is init correctly.
来源:https://stackoverflow.com/questions/26838957/why-can-i-not-get-a-properly-formatted-string-from-nsarray-element