There is an array of objects (Zakazchik):
#property (strong, nonatomic) NSMutableArray *zakazchikFavoritesArray;
Each object has field #property int zakazchikCategory and can vary from 1 to 23 inclusive.
How can I create a TableView, so grouping it was on this field?
ADDED:
in viewDidLoad (after filling zakazchikFavoritesArray):
dataDictionary = [NSMutableDictionary dictionary];
for (Zakazchik *object in zakazchikFavoritesArray) {
NSMutableArray *categoryArray = dataDictionary[#(object.zakazchikCategory)];
if (categoryArray == nil) {
categoryArray = [NSMutableArray array];
dataDictionary[#(object.zakazchikCategory)] = categoryArray;
}
[categoryArray addObject:object];
}
also:
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return dataDictionary.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSArray *array = dataDictionary[#(section)];
return array.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
Zakazchik *object = dataDictionary[#(indexPath.section)][#(indexPath.row)];
static NSString *CellIdentifier = #"ZakazchikCellFavorites";
ZakazchikCellFavorites *customCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
customCell.zakazchikName.text = object.zakazchikName;
return customCell;
}
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
Zakazchik *object = dataDictionary[#(section)];
return [NSString stringWithFormat:#"%i", object.zakazchikCategory];
}
i got error:
2015-05-30 myApp[12521:484566] -[__NSArrayM zakazchikCategory]: unrecognized selector sent to instance 0x7b735f00
2015-05-30 myApp[12521:484566] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM zakazchikCategory]: unrecognized selector sent to instance 0x7b735f00'
The most straightforward way to do this is to first organize your data in to a new data structure that sorts them by the category property. I would recommend using a dictionary that maps from category to an array of all objects that have that category value. You can transform your data like this:
NSMutableDictionary *dataDictionary = [NSMutableDictionary dictionary];
for (Zakazchik *object in zArray) {
NSMutableArray *categoryArray = dataDictionary[#(object.category)];
if (categoryArray == nil) {
categoryArray = [NSMutableArray array];
dataDictionary[#(object.zakazchikCategory)] = categoryArray;
}
[categoryArray addObject:object];
}
Then use this data structure when implementing your UITableView data source methods:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return dataDictionary.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *array = dataDictionary[#(section)];
return array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
Zakazchik *object = dataDictionary[#(indexPath.section)][#(indexPath.row)];
// Create your cell using the object..
}
- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSArray *array = dataDictionary[#(section)];
Zakazchik *firstObject = [array firstObject];
return [NSString stringWithFormat:#"%i", firstObject.zakazchikCategory];
}
To avoid error you can rewrite this method as follow
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSMutableArray *objectArray = dataDictionary[#(section)]; // not needed
return [NSString stringWithFormat:#"Category #%i", section];
}
Because your dataDictionary contains arrays of Zakazchik not objects directly and, I guess you have another table/array with names of categories so in this method no reason to select this object
Related
I'm making a title indexed event invitation list. I have an array with EventStatus objects. I'm making the _data array for table like,
for (int i = 0; i < eventStatusList.count; i++) {
NSString *firstName = ((OCEventStatus*)eventStatusList[i]).user.firstName;
[_sortedUsers setObject:((OCEventStatus*)eventStatusList[i]).user.firstName forKey:[firstName substringToIndex:1]];
}
_sortedUserTitles = [[[_sortedUsers allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] mutableCopy];
_data = [eventStatusList mutableCopy];
[self.dataTableView reloadData];
and I think this for loop thing is too slow. Is there a way to do this in a good manner? Following is the title index making up logic with UITablrViewDataSource methods.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return [_sortedUserTitles count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
NSString *sectionTitle = [_sortedUserTitles objectAtIndex:section];
NSArray *sectionUsers = [_sortedUsers objectForKey:sectionTitle];
return [sectionUsers count];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
// return animalSectionTitles;
return _alphabetArray;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
return [_sortedUserTitles indexOfObject:title];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [_sortedUserTitles objectAtIndex:section];
}
This is error because of in the _sortedUsers dictionary has a string instead of an array. How may I fix this? And also please suggest a fast, good manner to implement this title index.
If you want to create an List of Firstnames try this perhaps.
At interface:
#property(nonatomic, strong)NSMutableDictionary *dict;
#property(nonatomic, strong)NSMutableArray *alphabet;
_dict = [NSMutableDictionary new];
_alphabet = [NSMutableArray new];
[eventStatusList sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
OCEventStatus *ev1 = (OCEventStatus*)obj1;
OCEventStatus *ev2 = (OCEventStatus*)obj2;
return [ev1.firstName compare:ev2.firstName];
}];
for(OCEventStatus *state in eventStatusList){
NSString *firstchar = [[state.firstName substringToIndex:1] lowercaseString];
if([dict objectForKey:firstchar]==nil){
NSMutableArray *tmp = [NSMutableArray new];
[tmp addObject:state];
[_dict setObject:tmp forKey:firstchar];
[_alphabet addObject:firstChar];
}else{
[[dict objectForKey:firstchar] addObject:state];
}
}
Now you have an Array of firstnames in a Dictionary which has the first letter as the key for Example: a -> ["Alfred","Albert",...]
In the Datasource methods you have to return it like this...
-(NSInteger)numberOfSectionsInTableView:(UITableView*)tableView{
return dict.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection;(NSInteger)section
{
return [dict objectForKey:[alphabet objectAtIndex:section]].count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
OVEventStatus *state = [[dict objectForKey:[alphabet objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.text = state.firstName;
return cell;
}
Please try if this fits for you
Update:
If you also want to Sort the Arrays I would recommend to sort the eventListBy firstName first! So you have the correct order when you loop over the eventStatusList.
I get this json from web service and I need to group it depending on "PRICELISTCATEGORY" value. I tried the following code, but I get repeated rows and sections in the table. I collect the web service array in self.arrayPriceList. What am I doing wrong?
After collecting the array from json web service, I call [self didReceiveResponseJson:self.arrayPriceList];
-(NSMutableDictionary *)priceListCategoryDitionaryAllReadyExist:(NSString *)price {
for(NSMutableDictionary *priceListDict in self.arrayPriceList){
if([[[priceListDict objectForKey:#"PRICELISTCATEGORY"] objectForKey:#"text"] isEqualToString:price])
//return the existing array refrence to add
return priceListDict;
}
// if we dont found then we will come here and return nil
return nil;
}
-(void)didReceiveResponseJson:(NSMutableArray *)jsonArray {
for(NSDictionary *priceDict in jsonArray) {
NSMutableDictionary *existingPriceListDict=[self priceListCategoryDitionaryAllReadyExist:[[priceDict objectForKey:#"PRICELISTCATEGORY"] objectForKey:#"text"]];
NSMutableArray *existingTempArray = [NSMutableArray array];
if(existingPriceListDict != nil) {
//if name exist add in existing array....
[existingTempArray addObject:priceDict];
}
else {
// create new price list array
NSMutableArray *newPriceListArray=[[NSMutableArray alloc] init];
// Add name dictionary in it
[newPriceListArray addObject:priceDict];
// add this newly created pricelist array in globalNameArray
[self.arrayPriceList addObject:newPriceListArray];
}
}
//so at the end print global array you will get dynamic array with the there respetive dict.
//NSLog(#"Table array %#", self.arrayPriceList);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TGAPriceListCell *cell = [tableView dequeueReusableCellWithIdentifier:#"TGAPriceListCellId" forIndexPath:indexPath];
NSDictionary *dict;
if (self.isFiltered) {
dict = [self.arrayFilteredPriceList objectAtIndex:indexPath.row];
} else {
dict = [self.arrayPriceList objectAtIndex:indexPath.section];
}
cell.lblAPNBarCode.text = [[dict objectForKey:#"APNBARCODE"] objectForKey:#"text"];
cell.lblAvgCost.text = [[dict objectForKey:#"AVERAGECOST"] objectForKey:#"text"];
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (self.isFiltered) {
return self.arrayFilteredPriceList.count;
} else {
NSArray *arrayPrice = [self.arrayPriceList objectAtIndex:section];
return [arrayPrice count];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [self.arrayPriceList count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSDictionary *arrayPrice = [self.arrayPriceList objectAtIndex:section];
if([arrayPrice count]) {
return [[arrayPrice objectForKey:#"PRICELISTCATEGORY"] objectForKey:#"text"];
}
else
return nil;
}
After calling didReceiveResponseJson in viewDidLoad
self.arrayPriceList = [NSMutableArray array];
self.dictPriceList = [NSMutableDictionary dictionary];
I made changes in tableview datasource methods
-(void)didReceiveResponseJson:(NSMutableArray *)jsonArray {
for (NSDictionary *dict in jsonArray ) {
NSString *strPriceListCategory = [[dict objectForKey:#"PRICELISTCATEGORY"] objectForKey:#"text"];
if ([[self.dictPriceList allKeys] containsObject:strPriceListCategory]) {
NSMutableArray *arrayTemp = [self.dictPriceList objectForKey:strPriceListCategory];
[arrayTemp addObject:dict];
[self.dictPriceList setObject:arrayTemp forKey:strPriceListCategory];
} else {
NSMutableArray *arrayTemp = [[NSMutableArray alloc] initWithObjects:dict, nil];
[self.dictPriceList setObject:arrayTemp forKey:strPriceListCategory];
}
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TGAPriceListCell *cell = [tableView dequeueReusableCellWithIdentifier:#"TGAPriceListCellId" forIndexPath:indexPath];
NSDictionary *dict;
if (self.isFiltered) {
dict = [self.arrayFilteredPriceList objectAtIndex:indexPath.row];
} else {
NSArray *arrayPriceListAllKeys = [self.dictPriceList allKeys];
NSArray *arrayPrice = [self.dictPriceList objectForKey:[arrayPriceListAllKeys objectAtIndex:indexPath.section]];
dict = [arrayPrice objectAtIndex:indexPath.row];
}
cell.lblAPNBarCode.text = [[dict objectForKey:#"APNBARCODE"] objectForKey:#"text"];
cell.lblAvgCost.text = [[dict objectForKey:#"AVERAGECOST"] objectForKey:#"text"];
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (self.isFiltered) {
return self.arrayFilteredPriceList.count;
} else {
NSArray *arrayPriceListAllKeys = [self.dictPriceList allKeys];
NSArray *arrayPrice = [self.dictPriceList objectForKey:[arrayPriceListAllKeys objectAtIndex:section]];
return [arrayPrice count];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[self.dictPriceList allKeys] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *price = [[self.dictPriceList allKeys] objectAtIndex:section];
return price;
}
I'm sorting my array by last name alphabetically. I'd like to separate this into sections with the appropriate header above each section (A, B, C, etc.).
Here's what I've tried below:
// Here is where I refresh the data and sort it based on last name
- (void)refreshData {
[[PCMSSessionManager sharedSession] refreshPCMSDataWithCompletion:^(BOOL success, NSString *errorMessage, id resultObject) {
if (success) {
NSLog(#"yay!");
self.membersArray = [[PCMSSessionManager sharedSession] memberArr];
// Let's sort the array
self.sortedArray = [self.membersArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSString *first = [(PCMSMember*)a lastName];
NSString *second = [(PCMSMember*)b lastName];
return [first compare:second];
}];
[self.tableView reloadData];
} else {
NSLog(#"boooo!!!!");
}
}];
}
- (NSDictionary *)indexedMembers
{
NSMutableDictionary *indexedContacts = [NSMutableDictionary new];
for (PCMSMember *member in self.sortedArray)
{
NSString *sortString = member.lastName;
NSString *sortLetter = [sortString substringToIndex:1];
/* see if that letter already exists as an index */
BOOL foundKey = NO;
for (NSString *key in [indexedContacts allKeys])
{
if ([key isEqualToString:sortLetter])
{
foundKey = YES;
}
}
NSMutableArray *valueArray;
if (foundKey)
{
valueArray = [((NSArray *)indexedContacts[sortLetter]) mutableCopy];
}
else
{
valueArray = [NSMutableArray new];
}
[valueArray addObject:member];
indexedContacts[sortLetter] = [valueArray copy];
}
return [indexedContacts copy];
}
// Here's my table data
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[[self indexedMembers] allKeys] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSDictionary *indexedContacts = [self indexedMembers];
NSArray *myKeys = [indexedContacts allKeys];
NSString *key = myKeys[section];
return [((NSArray *)[self indexedMembers][key]) count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"cellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
// Configure the cell...
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if (self.isPhysician == YES) {
NSString *key = [[self indexedMembers] allKeys][indexPath.section];
PCMSMember *currentMember = ((NSArray *)[self indexedMembers][key])[indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"%# %#", currentMember.firstName, currentMember.lastName];
}
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [[self indexedMembers] allKeys][section];
}
UPDATE:
This is getting me closer to what I want.
The data is loading, it's being grouped properly and the headers are showing.
But it's not in alphabetical order.
How can I improve this code to show alphabetically?
It's showing in alphabetical order in my console, just not in the app.
The NSMutableDictionary is unordered by definition. It is not the natural choice if you rely on the order of the stored objects. I suggest you to use NSMutableArray instead. To store the tableview data for each section you can use this mini class
#interface MembersWithSameInitial : NSObject
#property (strong) NSString* initial;
#property (strong) NSMutableArray<PCMSMember*>* members;
#end
#implementation MembersWithSameInitial
#end
After you have sorted the members, all the data for the tableview can be produced with this before tableView reload.
NSMutableArray<MembersWithSameInitial*>* groupedMembers = [[NSMutableArray alloc] init];
for (PCMSMember* member in sortedArray) {
NSString* inicial = [member.lastName substringToIndex:1];
MembersWithSameInitial* last = [groupedMembers lastObject];
if (last && [last.initial isEqualToString:inicial]) {
[last.members addObject:member];
} else {
MembersWithSameInitial* newGroup = [[MembersWithSameInitial alloc] init];
newGroup.initial = inicial;
newGroup.members = [[NSMutableArray alloc] initWithObjects:member, nil];
[groupedMembers addObject:newGroup];
}
}
Since the structure of groupedMembers fits to a grouped tableView, the dataSource methods will have trivial implementations. Assuming, that you have stored groupedMembers in a property.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.groupedMembers.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.groupedMembers[section].members.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//...
PCMSMember *currentMember = self.groupedMembers[indexPath.section].members[indexPath.row];
//...
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return groupedMembers[section].initial;
}
Suggestion:
Create two properties
#property NSMutableArray *keys; // for the letters in alphabetical order
#property NSMutableDictionary *indexedContacts; // same as your implementation.
In the method refreshData call the method to create the data source and then reload the table view on the main thread.
Actually you don't need the properties memberArray and sortedArray anymore. The sorted array is passed to the method to create the data source.
- (void)refreshData {
[[PCMSSessionManager sharedSession] refreshPCMSDataWithCompletion:^(BOOL success, NSString *errorMessage, id resultObject) {
if (success) {
NSLog(#"yay!");
self.membersArray = [[PCMSSessionManager sharedSession] memberArr];
// Let's sort the array
NSArray *sortedArray = [self.membersArray sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSString *first = [(PCMSMember*)a lastName];
NSString *second = [(PCMSMember*)b lastName];
return [first compare:second];
}];
[self indexMembers:sortedArray];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
} else {
NSLog(#"boooo!!!!");
}
}];
}
The method indexMembers initializes the properties keys and indexedContacts and creates the data source.
- (void)indexMembers:(NSArray *)sortedMembers
{
self.keys = [[NSMutableArray alloc] init];
self.indexedContacts = [[NSMutableDictionary alloc] init];
for (PCMSMember *member in sortedMembers)
{
NSString *sortString = member.lastName;
NSString *sortLetter = [sortString substringToIndex:1];
/* see if that letter already exists as an index */
NSArray *keyArray = self.indexedContacts[sortLetter];
NSMutableArray *valueArray;
if (keyArray) {
// array for key exists, use it
valueArray = [keyArray mutableCopy];
} else {
// array for key does not exist, create a new one
valueArray = [NSMutableArray new];
// and add the letter to keys
[self.keys addObject:sortLetter];
}
[valueArray addObject:member];
self.indexedContacts[sortLetter] = [valueArray copy];
}
}
numberOfSectionsInTableView returns the number of keys
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.keys.count;
}
numberOfRowsInSection gets the appropriate array for the given section and returns the number of items.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *letter = self.keys[section];
NSArray *memberArray = self.indexedContacts[letter];
return memberArray.count;
}
In cellForRowAtIndexPath use the method dequeueReusableCellWithIdentifier: forIndexPath: to get always a valid cell. Then like in numberOfRowsInSection get the actual member array and populate the label.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"cellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
// Configure the cell...
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
if (self.isPhysician == YES) {
NSString *letter = self.keys[indexPath.section];
NSArray *memberArray = self.indexedContacts[letter];
PCMSMember *currentMember = memberArray[indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"%# %#", currentMember.firstName, currentMember.lastName];
}
return cell;
}
titleForHeaderInSection simply returns the letter for the section
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return self.keys[section];
}
You're calling indexedMembers too much. This is very expensive.
I couldn't test the code, maybe there is a self or something else missing but you get an impression of the workflow.
I have a very simple app to learn how to work with sections in UITableView but there is an exception -
2013-09-17 08:46:19.956 Sections[4497:c07] * -[__NSArrayI
objectAtIndex:]: message sent to deallocated instance 0x9566d40
The whole methods are below - need help.
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:#"sortednames" ofType:#"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
self.names = dict;
NSArray *array = [[_names allKeys] sortedArrayUsingSelector:#selector(compare:)];
_keys = array;
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
NSLog(#"%lu", (unsigned long)[_keys count]);
return [_keys count];
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *key = [_keys objectAtIndex:section];
NSArray *nameSection = [_names objectForKey:key];
return [nameSection count];
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [_keys objectAtIndex:section];
NSArray *nameSection = [_names objectForKey:key];
static NSString *SectionsTableIdentifier = #"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SectionsTableIdentifier];
}
cell.textLabel.text = [nameSection objectAtIndex:row];
return cell;
}
- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSString *key = [_keys objectAtIndex:section];
return key;
}
You must retain _keys array like that:
_keys = [[[_names allKeys] sortedArrayUsingSelector:#selector(compare:)] retain];
Here you are first taking values in other array and then passing it to _keys..thats not proper way of doing it..
just directly pass the values to _keys like below
_keys = [[_names allKeys] sortedArrayUsingSelector:#selector(compare:)];
also check for self.names, you are doing the same thing there.
Hope this will help you.
dictionaryOfWebsites = [[NSMutableDictionary alloc] init];
[dictionaryOfWebsites setObject:#"http://www.site1.com" forKey:#"Site1"];
[dictionaryOfWebsites setObject:#"http://www.site2.com" forKey:#"Site2"];
[dictionaryOfWebsites setObject:#"http://www.site3.com" forKey:#"Site3"];
[dictionaryOfWebsites setObject:#"http://www.site4.com" forKey:#"Site4"];
Above is my dictionary. I want to have a tableview where the text in the UITableViewCell will say "Site1" and the subtext will have the URL.
I know this will get me all the keys
NSArray *keys = [dictionaryOfWebsites allKeys];
// values in foreach loop
for (NSString *key in keys) {
NSLog(#"%# is %#",key, [dict objectForKey:key]);
}
you're help would be greatly appreciated
If my approach is not the best one, please let me know so I can learn from your recommendations.
Try
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [[dictionaryOfWebsites allKeys] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Initialize cell of style subtitle
NSArray *keys = [[dictionaryOfWebsites allKeys]sortedArrayUsingSelector:#selector(compare:)];
NSString *key = keys[indexPath.row];
cell.textLabel.text = key;
cell.detailTextLabel.text = dictionaryOfWebsites[key];
return cell;
}
Edit : It is better to have an array of dictionaries for these kind of representation.
Each dictionary with two key value pairs Title and Subtitle.
self.dataArray = [NSMutableArray array];
NSDictionary *dict = #{#"Title":#"Site1",#"Subtitle":#"http://www.site1.com"};
[dataArray addObject:dict];
//Add rest of the dictionaries to the dataArray
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.dataArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Initialize cell of style subtitle
NSDictionary *dict = self.dataArray[indexPath.row];
cell.textLabel.text = dict[#"Title"];
cell.detailTextLabel.text = dict[#"Subtitle"];
return cell;
}
You could try:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//cell initialization code
NSString *title = [keys objectAtIndex:indexPath.row];
cell.textLabel.text = title;
cell.detailTextLabel.text = [dictionaryOfWebsites objectForKey:title];
return cell;
}
in that case declare keys array as a property.