How to get NSDictionary data into a UITableView
NSString *providerNameString = [self.providersDict objectForKey:@"provider"];
NSString *providerIdString = [self.providersDict objectForKey:@"object"];
You have initialized self.providersDict with keys 1, 2, 3. So you should Try to fetch providerNameString
using those keys and not @"provider"
same for providerIdString
.
Try
NSString *key = [self.providersDict allKeys][indexPath.row];
NSString *providerNameString = self.providersDict[key];
NSString *providerIdString = key;
cell.textLabel.text = providerNameString;
cell.detailTextLabel.text = providerIdString;
And don't forget to call [tableView reloadData];
once your self.providersDict
is initialized.
As for a suggestion why dont you create a Model Class for Provider
with id, name and other information. You can add each provider in an array and would make your life a lot easier.
hanumanDev
Updated on June 04, 2022Comments
-
hanumanDev almost 2 years
I have 2 NSArrays that I'm trying to link together in an NSDictionary so that each providerName has a providerId associated with it.
I expected the two arrays to be associated with each other using
self.providersDict = [NSDictionary dictionaryWithObjects:providerName forKeys:providerId];
and then the providerName to be displayed as the table cell title and the id as the table cell subtitle.At the moment I can't get the data displayed on the UITable or even log out the dictionary using:
for (id key in self.providersDict) { NSLog(@"key: %@, value: %@", key, [self.providersDict objectForKey:key]); }
declared in the .h:
NSArray *providerName; NSArray *providerId; @property (nonatomic, strong) NSDictionary *providersDict;
and in the viewDidLoad:
providerName = [NSArray arrayWithObjects:@"provider1", @"provider2", @"provider3", nil]; providerId = [NSArray arrayWithObjects:@"1", @"2", @"3", nil]; self.providersDict = [NSDictionary dictionaryWithObjects:providerName forKeys:providerId];
the UITable methods:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [[self.providersDict allKeys] count]; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *unifiedID = @"aCellID"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:unifiedID]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:unifiedID]; } for (id key in self.providersDict) { NSLog(@"key: %@, value: %@", key, [self.providersDict objectForKey:key]); } NSString *providerNameString = [self.providersDict objectForKey:@"provider"]; NSString *providerIdString = [self.providersDict objectForKey:@"object"]; cell.textLabel.text = providerNameString; cell.detailTextLabel.text = providerIdString; return cell; }
thanks for the help.
-
Anupdas about 11 yearsYou already thanked me by upvoting. But again if you can try to create a model object for Provider :)