Why can I not get a properly formatted string from NSArray element?

╄→гoц情女王★ 提交于 2020-01-06 13:55:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!