I am new coding in Objective-C and I am trying to figure out how to do the following:
I have a class Company:
@interface Company : NSObject
@property (strong, nonatomic)NSString *companyID;
@property (strong, nonatomic)NSString *companyName;
@end
I am getting a dictionary from a server and just parsing in objects. After that, I am adding these objects in an array (It´s working - no problem here - I got the 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];
}
THE PROBLEM IS: I need to access the objects and its fields inside
companyInformationArray
I am just trying to do something similar with (these two approaching will not work of course):
Company *company = [Company new];
company = [[companyInformationArray objectAtIndex:0] valueForKey:@"name"];
Or:
Company *company = [Company new];
company.companyName = [[companyInformationArray objectAtIndex:0] companyName];
Could you please help me?
Thanks!
Objective-C now supports lightweight generics. For example, rather than a simple NSMutableArray, you can specify that your array is an array of Company objects:
NSMutableArray <Company *> *companyInformationArray;
Then you can do something like:
NSString *nameOfSecondCompany = companyInformationArray[1].companyName;
The virtue of this is that the compiler will warn you if you try to add something that isn't a Company and likewise you enjoy strong typing of the properties without any casting.
Off the top of my head (not running it to test)...
// 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With