Developing a iPAD app, where I'm trying to populate table, This is how i'm doing:
In view did load, I'm creating two dictionary object and adding object as Pdf and Excel.
- (void)viewDidLoad
{
[super viewDidLoad];
arrDocuments = [[NSMutableArray alloc] init];
NSArray *arr1 = [NSArray arrayWithObjects:#"PDF", nil];
NSDictionary *pdf = [NSDictionary dictionaryWithObjects:arr1 forKeys:nil];
NSArray *arr2 = [NSArray arrayWithObjects:#"Excel", nil];
NSDictionary *excel = [NSDictionary dictionaryWithObjects:arr2 forKeys:nil];
[arrDocuments addObject:pdf];
[arrDocuments addObject:excel];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [arrDocuments count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
//return [arrReceipes count];
NSDictionary *dictionary = [arrDocuments objectAtIndex:section];
NSArray *array = [dictionary objectForKey:[self.sortedKeys objectAtIndex:section]];
return [array count];
}
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = #"MyIdentifier";
UITableView *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell ==nil) {
cell = [[UITableViewCell alloc]initWithFrame:CGRectZero reuseIdentifier:MyIdentifier];
}
return cell;
}
With this implementation I'm not able to see table view.Its going to main method and showing me SIGABRT message.Where I'm going wrong??
While creating NSDictionary, you have passed nil in place of keys array,
NSDictionary *pdf = [NSDictionary dictionaryWithObjects:arr1 forKeys:nil];
You should give proper objects and keys to the dictionary. This method expects objects and keys to be given in an array as you can see in its method signature.
+ (instancetype)dictionaryWithObjects:(NSArray *)objects forKeys:(NSArray *)keys
Related
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.
Hi I am trying to display detail information of json data in second table view but their is some mistake in my logic so please help me my json response is in image and I am trying to to dispaly channel response in table view when user click the same cat_id then display all related channel list and image in second tableViewcell please help me..
-(void)getCategories
{
Service *srv=[[Service alloc]init];
NSString *str=#"http://streamtvbox.com/site/api/matrix/";//?country_code=91&phone=9173140993&fingerprint=2222222222";
NSString *method=#"channels";
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[srv postToURL:str withMethod:method andParams:dict completion:^(BOOL success, NSDictionary *responseObj)
{
NSDictionary *dict = [[NSDictionary alloc]initWithDictionary:[responseObj valueForKey:#"categories"]];
arrayChannelList=[responseObj valueForKey:#"channels"];
NSLog(#"Array : %#",channels);
for (NSDictionary *dict in arrayChannelList)
{
//NSArray *tempTitle = [[NSArray alloc]init];
arrayCat_Id = [dict objectForKey:#"cat_id"];
}
tempArray = [[NSArray alloc]init];
tempArray = [dict allKeys];
for(int i=0; i<tempArray.count; i++)
{
[arrayCategories addObject:[dict valueForKey:[tempArray objectAtIndex:i]]];
}
NSLog(#"%#",arrayCategories);
[tblView reloadData];
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"%lu",(unsigned long)[arrayCategories count]);
return arrayCategories.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"ChannelCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [arrayCategories objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
DetailChannelsViewController *detailVC = (DetailChannelsViewController *)[self.storyboard instantiateViewControllerWithIdentifier:#"DetailView"];
detailVC.channelTitle = [arrayCategories objectAtIndex:indexPath.row];
detailVC.SubChannelName = arrayCat_Id;
NSLog(#"%#",arrayCat_Id);
[self.navigationController pushViewController:detailVC animated:YES];
}
Just initialize of your NSmutuableArray and add the value of with addobject like:-
arrayCat_Id=[[NSMutableArray alloc]init];
for(your logic){
[arrayCat_Id addobject:[dict objectForKey:#"cat_id"];
}
I am using the following sample code to have the section contents in "Grouped Table View". Showing the contents in "Grouped Table View" is fine.
But, the issue is, it sorts the section content based on alphabetical order, so the order of section header content is not displaying as expected. For example: I want "About" to be shown at the end of section in tableview, but here it is always shows first (because of alphabetical sort does there). How can i display the section content based on the below code without alphabetical sorting. Please advise!
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *arrTemp4 = [[NSArray alloc]initWithObjects:#"Quick Logon",#"Stay Logged On", nil];
NSArray *arrTemp3 = [[NSArray alloc]initWithObjects:#"Notifications",#"Text Messaging",#"Family Members",#"Social Media",nil];
NSArray *arrTemp2 = [[NSArray alloc]initWithObjects:#"Payment Accounts",nil];
NSArray *arrTemp1 = [[NSArray alloc]initWithObjects:#"Phone Nickname",#"Version",nil];
NSDictionary *temp = [[NSDictionary alloc]initWithObjectsAndKeys: arrTemp1,#"About", arrTemp2,#"Payment Preferences", arrTemp3,#"Profile & Preferences", arrTemp4,#"Security ", nil];
self.tableContents = temp;
NSLog(#"table %#",self.tableContents);
NSLog(#"table with Keys %#",[self.tableContents allKeys]);
self.sortedKeys = [[self.tableContents allKeys] sortedArrayUsingSelector:#selector(compare:)];
NSLog(#"sorted %#",self.sortedKeys);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return [self.sortedKeys count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [self.sortedKeys objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
NSArray *listData =[self.tableContents objectForKey:[self.sortedKeys objectAtIndex:section]];
return [listData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
NSArray *listData =[self.tableContents objectForKey:[self.sortedKeys objectAtIndex:[indexPath section]]];
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier];
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
cell.accessoryType = indexPath.section > 0 ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
NSUInteger row = [indexPath row];
cell.textLabel.text = [listData objectAtIndex:row];
NSLog(#"indexPath.section %d",indexPath.section);
if ( indexPath.section==0 )
{
// cell.imageView.image = [UIImage imageNamed:#"icon.png"];
}
//cell.switch.hidden = indexPath.section > 0;
return cell;
}
Thanks in Advance!
Don't use sortedArrayUsingSelector:. Instead, explicitly create the key array in the order that you want. Then, create tableContents using that key array and another array created to hold all of your content arrays (using dictionaryWithObjects:forKeys:).
NSArray *keys = #[ #"About", #"Payment Preferences", #"Profile & Preferences", #"Security" ];
NSArray *values = #[ arrTemp1, arrTemp2, arrTemp3, arrTemp4 ];
self.tableContents = [NSDictionary dictionaryWithObjects:values forKeys:keys];
self.sortedKeys = keys;
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.
I am trying to learn how to code a UITableView and is having some problems with the programming of the section.
I have declared 3 arrays with strings and 1 array with the 3 arrays.
firstSection = [NSArray arrayWithObjects:#"Red", #"Blue", nil];
secondSection = [NSArray arrayWithObjects:#"Orange", #"Green", #"Purple", nil];
thirdSection = [NSArray arrayWithObject:#"Yellow"];
array = [[NSMutableArray alloc] initWithObjects:firstSection, secondSection, thirdSection, nil];
To shows the headers
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
NSString * title;
title = [NSString stringWithFormat:#"%#" , [array objectAtIndex:section]];
return title;
}
which shows the array itself as the headers
therefore is it possible to actually show the name of the sections using the names of the arrays such as firstSection and secondSection?
In your case, it's better to store your arrays in an NSDictionary. For example, if you declare and synthesize an NSDictionary variable called tableContents and an NSArray called titleOfSections, you can do something like this:
- (void)viewDidLoad {
[super viewDidLoad];
//These will automatically be released. You won't be needing them anymore (You'll be accessing your data through the NSDictionary variable)
NSArray *firstSection = [NSArray arrayWithObjects:#"Red", #"Blue", nil];
NSArray *secondSection = [NSArray arrayWithObjects:#"Orange", #"Green", #"Purple", nil];
NSArray *thirdSection = [NSArray arrayWithObject:#"Yellow"];
//These are the names that will appear in the section header
self.titleOfSections = [NSArray arrayWithObjects:#"Name of your first section",#"Name of your second section",#"Name of your third section", nil];
NSDictionary *temporaryDictionary = [[NSDictionary alloc]initWithObjectsAndKeys:firstSection,#"0",secondSection,#"1",thirdSection,#"2",nil];
self.tableContents = temporaryDictionary;
[temporaryDictionary release];
}
Then in the table view controller methods:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return [self.titleOfSections count];
}
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
return [[self.tableContents objectForKey:[NSString stringWithFormat:#"%d",section]] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//Setting the name of your section
return [self.titleOfSections objectAtIndex:section];
}
Then to access the contents of each array in your cellForRowAtIndexPath method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
NSArray *arrayForCurrentSection = [self.tableContents objectForKey:[NSString stringWithFormat:#"%d",indexPath.section]];
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:SimpleTableIdentifier] autorelease];
}
cell.textLabel.text = [arrayForCurrentSection objectAtIndex:indexPath.row];
return cell;
}
can u do like this
NSArray *SectionArray = [[NSArray alloc]initwithArray:[array objectAtIndex:section]];
NSString * title;
title = [NSString stringWithFormat:#"%#" , [SectionArray objectAtIndex:section]];
return title;