我是Objective-C的新编码,我正在试图弄清楚如何执行以下操作:
我有一个班级Company
:
@interface Company : NSObject
@property (strong, nonatomic)NSString *companyID;
@property (strong, nonatomic)NSString *companyName;
@end
我从服务器获取字典,只是解析对象。 之后,我将这些对象添加到一个数组中(它正在工作 - 这里没问题 - 我得到了JSON)。
NSMutableDictionary *companyDictionary = [[NSMutableDictionary alloc]initWithDictionary:response];
NSArray *companyArray = [companyDictionary valueForKey:@"data"];
NSMutableArray *companyInformationArray = [NSMutableArray new];
//Parser
for (int i = 0; i < [companyArray count]; i++) {
Company *company = [Company new];
company.companyID = [[companyArray objectAtIndex:i] valueForKey:@"company_id"];
company.companyName = [[companyArray objectAtIndex:i] valueForKey:@"name"];
[companyInformationArray addObject:company];
}
问题是:我需要访问
中的对象及其字段companyInformationArray
我只是想尝试做类似的事情(这两个接近当然不起作用):
Company *company = [Company new];
company = [[companyInformationArray objectAtIndex:0] valueForKey:@"name"];
或者:
Company *company = [Company new];
company.companyName = [[companyInformationArray objectAtIndex:0] companyName];
你能帮我吗?
谢谢!
答案 0 :(得分:6)
Objective-C现在支持轻量级泛型。例如,您可以指定您的数组是NSMutableArray
个对象的数组,而不是简单的Company
:
NSMutableArray <Company *> *companyInformationArray;
然后你可以做类似的事情:
NSString *nameOfSecondCompany = companyInformationArray[1].companyName;
这样做的好处是,如果你尝试添加一些不是Company
的东西,编译器会发出警告,同样你也喜欢强大的属性输入而不需要任何强制转换。
答案 1 :(得分:3)
脱离我的头顶(没有运行它来测试)......
// get the Company object at slot [0] in the array of Company objects
Company *company = (Company *)[companyInformationArray objectAtIndex:0];
// now use the properties...
myNameLabel.text = company.companyName;
myIDLabel.text = company.companyID;