Accessing objects and their properties inside an array of objects in Objective-C
I am new code 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 fetching a dictionary from the server and just parsing the objects. After that, I add these objects to the array (it works - no problem here - I got 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];
}
PROBLEM: I need to access objects and their fields inside
companyInformationArray
I'm just trying to do something like this (these two approaches won't 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 help me?
Thank!
source to share
Off the top of my head (don't run 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;
source to share
Objective-C now supports lightweight generics. For example, instead of simple, NSMutableArray
you can specify that your array is an array of objects Company
:
NSMutableArray <Company *> *companyInformationArray;
Then you can do something like:
NSString *nameOfSecondCompany = companyInformationArray[1].companyName;
The good thing about this is that the compiler will warn you if you try to add something that is not Company
, and you also like strong property printing without casting.
source to share