为什么我不能从NSArray元素中获取格式正确的字符串? [英] Why can I not get a properly formatted string from NSArray element?

查看:67
本文介绍了为什么我不能从NSArray元素中获取格式正确的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从核心数据模型中检索属性,并将获取的字符串放入导航栏的标题中。我一定做错了,因为我无法将检索到的字符串设置为标题,但是如果我手动输入字符串,则可以设置标题。

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);

当我使用self.tabBarController.title = area_name设置标题时;我得到 NSArrayI stringByTrimmingCharactersInSet:]:无法识别的选择器发送到实例,并且在将其设置为测试变量时设置得很好。

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.

我还注意到NSLog for变量test是 test,而area_name的NSLog输出是:( Single Area)

I also noticed that the NSLog for the variable test is "test" whereas the NSLog output for area_name is: ( "Single Area" )

这是因为我要从数组中检索我的area_name吗?我应该改用字典吗?

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.

谢谢。

推荐答案

这里是错误的

NSString *area_name = [area valueForKey:@"name"];  

区域对象的类型为 NSArray 包含 Area 对象。

因此,您需要从该数组中获取元素,然后读取名称

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);

这篇关于为什么我不能从NSArray元素中获取格式正确的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆