Actually this is to follow up my question before
UITableView show only first row.
Now my problem is that I only want to view the 10 list in my plist. If there are 11 items, the first item will be replace by the second and so on so my list only 10 items.
And this is my code to save to the plist:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"Data.plist"];
NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:plistPath];
if (nil == array) {
array = [[NSMutableArray alloc] init];
}
NSMutableArray *list = [[NSMutableArray alloc]init];
[list addObject:resi.text];
[array addObject:list];
[array writeToFile:plistPath atomically: TRUE];
And this is the whole code for my table view that have been modified
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSArray *list = (NSArray *)[self.array objectAtIndex:indexPath.row];
if(list && [list count] > 0) { //to check and avoid any crash
cell.textLabel.text = [list objectAtIndex:0];
}
// Configure the cell...
return cell;
}
- (void)viewWillAppear:(BOOL)animated
{
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"Data.plist"];
array = [NSMutableArray arrayWithContentsOfFile:plistPath];
[myHistoryTable reloadData];
}
if ([array count] > 10) {
array = [array subarrayWithRange:NSMakeRange([array count] - 10, 10)];
}
if you don't want to overwrite the original array create a second one which serves as the dataSource of the tableView:
array = /* load from plist */;
if ([array count] > 10) {
self.dataSourceArray = [array subarrayWithRange:NSMakeRange([array count] - 10, 10)];
}
else {
self.dataSourceArray = array;
}
Related
I have a tableview that the rows are been filled with the name of .csv files that are in the document directory, i need to open the .csv that is been selected in the row and then show the info in a detail view. I'm trying to get the indexPath.row that it's been selected to get the correct element in the array but is crashing here's is that part of the code and above i will post the full code:
-(UITableViewCell *)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%d", indexPath.row);
currentcsvfile = [dirList objectAtIndex:indexPath.row ];;
NSLog(#"\n current csv %#",currentcsvfile);
[self performSegueWithIdentifier:#"detailsegue" sender:self];
}
This is the error:
2017-10-09 22:51:31.590248 oFiOSstoryboard[2340:583894] 2
2017-10-09 22:51:31.590460 oFiOSstoryboard[2340:583894] *** -[__NSArrayI objectAtIndex:]: message sent to deallocated instance 0x170246540
![error
]1
Here is the full code:
#import "CameraViewController.h"
#import "resultsDetailView.h"
#interface CameraViewController ()
#property (strong, nonatomic) IBOutlet UITableView *data;
#property (retain, nonatomic) IBOutlet UILabel *timeStamp;
#end
////////////////////////csv readder
NSMutableArray *tableDataArray;
NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSFileManager *manager = [NSFileManager defaultManager];
NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:bundleRoot];
NSString *filename;
NSMutableArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *strPath = [[NSBundle mainBundle] pathForResource:#"file" ofType:#"csv"];
NSString *strFile = [NSString stringWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:nil];
NSMutableArray *timeStampb = [[NSMutableArray alloc] init]; ;
NSMutableArray *arrayToDelete = [[NSMutableArray alloc] init]; ;
NSMutableArray *filePathsArray ;
NSMutableArray *dirList= [[NSMutableArray alloc] init]; ;
NSString *currentcsvfile;
#implementation CameraViewController
#synthesize data;
- (void)viewDidLoad {
[super viewDidLoad];
// ////lista de documentos
self.data.scrollEnabled = YES;
self.data.delegate = self;
self.data.dataSource = self;
filePathsArray =[[NSMutableArray alloc] init]; ;
NSMutableArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
NSMutableArray* fileList = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
//--- Listing file by name sort
NSLog(#"\n File list %#",fileList);
//---- Sorting files by extension
NSMutableArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF EndsWith '.csv'"];
filePathsArray = [filePathsArray filteredArrayUsingPredicate:predicate];
NSLog(#"\n\n Sorted files by extension %#",filePathsArray);
dirList = filePathsArray;
NSString *docPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
if (!strFile) {
NSLog(#"Error reading file.");
}
[timeStampb release];
timeStampb = [[NSMutableArray alloc] initWithArray:[strFile componentsSeparatedByString:#"\,"]];
// this .csv file is seperated with new line character
// if .csv is seperated by comma use "," instesd of "\n"
for(NSString *countryname in timeStampb) {
NSLog(#"%#", timeStampb);
}
}
////////////////////////////////////////////////////////////////Delete csv files
//- (IBAction)delet:(id)sender {
// NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
//
// NSString *filePath = [docPath stringByAppendingPathComponent:#"jorge.csv"];
// NSError *error = nil;
// [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
//}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
# pragma – mark table view DataSource Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dirList count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier ];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
UIColor* color = [UIColor colorWithRed:(254.0/255.0) green:(251.0/255.0) blue:(248.0/255.0) alpha:1];
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor colorWithRed:(253.0/255.0) green:(0.0/255.0) blue:(237.0/255.0) alpha:1];
[cell setSelectedBackgroundView:bgColorView];
cell.backgroundColor = color;
}
cell.textLabel.text = [timeStampb objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [dirList objectAtIndex:indexPath.row];
cell.textLabel.textColor = [UIColor colorWithRed:(0.0/255.0) green:(0.0/255.0) blue:(0.0/255.0) alpha:1];
cell.textLabel.font=[UIFont systemFontOfSize:8.0];
cell.detailTextLabel.font=[UIFont systemFontOfSize:15.0];
cell.detailTextLabel.textColor = [UIColor colorWithRed:(235.0/255.0) green:(120.0/255.0) blue:(33.0/255.0) alpha:1];
return cell;
}
-(UITableViewCell *)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%d", indexPath.row); // you can see selected row number in your console;
currentcsvfile = [dirList objectAtIndex:indexPath.row ];;
NSLog(#"\n current csv %#",currentcsvfile);
[self performSegueWithIdentifier:#"detailsegue" sender:self];
}
- (IBAction)deleteRow:(id)sender {
//we are not in edit mode yet
if([self.data isEditing] == NO){
//up the button so that the user knows to click it when they
//are done
[self.data setTitle:#"Done"];
//set the table to editing mode
[self.data setEditing:YES animated:YES];
}else{
//we are currently in editing mode
//change the button text back to Edit
//take the table out of edit mode
[self.data setEditing:NO animated:YES];
}
}
#pragma mark – TableView delegate
- (void)dealloc {
[_timeStamp release];
[dirList release];
self.data.delegate = nil;
self.data.dataSource = nil;
[super dealloc];
}
#end
When you get the array back from the file manager, retain it.
Also, there's no need for filePathsArray =[[NSMutableArray alloc] init]; ; since you are about to overwrite it with the returned results.
At line
dirList = filePathsArray;
You put autorelease object into variable ‘dirList’. Also you have a memory leak here.
If you need to put any objects from one array to other, use method addObjectsFromArray:. If you need to put other array into variable, use release/retain routine (Memory management in Objective-C)
New to coding and trying to create a simple check list (like a shopping list) for part of my iOS programme. Selecting a cell changes the accessory icon ok and changing the BOOL value in the dictionary manually before running the simulator also changes the acc' icon fine. So the problem seems to be with the code for altering the BOOL value in the plist after a cell is selected. Any help would massively appreciated. As I said pretty new to it so apologies for any shoddy code or obvious mistakes.
*CODE EDITED SO NO LONGER READING AND WRITING LIST FROM MAIN BUNDLE
#import "CheckListViewController.h"
#import "ListItem.h"
#interface CheckListViewController ()
#end
#implementation CheckListViewController
{
NSMutableArray *eventList;
}
#synthesize tableView = _tableView;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* dataPath = [documentsDirectory stringByAppendingPathComponent:#"CheckList.plist"];
if ( ![[NSFileManager defaultManager] fileExistsAtPath:dataPath]) {
NSString* resourceaPath = [[NSBundle mainBundle] pathForResource:#"CheckList" ofType:#"plist"];
[[NSFileManager defaultManager] copyItemAtPath:resourceaPath toPath:dataPath error:NULL];
}
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"CheckList.plist"];
NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
ListItem *listItem1 = [ListItem new];
listItem1.itemName = #"Read Guide";
listItem1.itemSelected = [dict valueForKey:#"Read Guide"];
.....
eventList = [NSMutableArray arrayWithObjects:listItem1, listItem2, listItem3, listItem4, listItem5, listItem6, listItem7, listItem8, nil];
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//Return the number of rows in the section.
return eventList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
ListItem *listItem = [eventList objectAtIndex:indexPath.row];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
if (listItem.itemSelected == [NSNumber numberWithBool:YES]) {
(cell.accessoryType = UITableViewCellAccessoryCheckmark);
} else {
(cell.accessoryType = UITableViewCellAccessoryNone);
}
}
cell.textLabel.text = listItem.itemName;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:NO];
ListItem *listItem = [eventList objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView cellForRowAtIndexPath: indexPath];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"CheckList.plist"];
NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
if (cell.accessoryType == UITableViewCellAccessoryNone) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
// Reflect selection in data model
[dict setObject:[NSNumber numberWithBool:YES] forKey:listItem.itemSelected];
[dict writeToFile:path atomically:YES];
} else if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
// Reflect deselection in data model
[dict setObject:[NSNumber numberWithBool:NO] forKey:listItem.itemSelected];
[dict writeToFile:path atomically:YES];
}
}
#end
Sorry for the massive chunk of code but thought any of it could potentially be problematic.
It looks like the path you are saving to and load from are different. You are loading from a bundle path, and then saving to a relative path with writeToFile:atomically. If my guess is correct, the default path for that method is not back into the bundle, but the documents directory of the app. On iOS, you cannot write back to the main bundle, so there a very good chance the file is not being saved where you think it is.
This question already has answers here:
Objective-C: how to add a new cell for each filename in UiTableView?
(2 answers)
Closed 9 years ago.
Bellow I have some code that retrieves files from the documents directory where my application is stored on the idevice. It then successfully retrieves that path to the file which is a mp4 because that is what I am storing. And does this by displaying the filename in a cell of the UiTableView I have created . However the code only displays one file in one cell. But I want to list multiple files individually in there own cell so eventually the user can individually select that cell depending on the video file they want.
Here is the code that retrieves and displays the file directory of the file but does not list more then one file in the table:
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if(!filePathsArray) // if data loading has been completed, return the number of rows ELSE return 1
{
if ([filePathsArray count] > 0)
return [filePathsArray count];
else
return 1;
}
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MainCell"];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
cell.textLabel.text = [filePathsArray[indexPath.row] lastPathComponent];
return cell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if(!filePathsArray)
{
if ([filePathsArray count] > 0)
return [filePathsArray count];
else
return 1;
}
return 1;
}
Should read:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [filePathsArray count];
}
You should be returning [filePathsArray count]; from your numberOfRowsInSection method under normal circumstances. Right now you're actually returning 1 from that method in all cases. I'm not sure what exactly you're trying to do with the logic at the top of your numberOfRowsInSection method, but I think you should start by just replacing the whole body of the method with return [filePathsArray count];.
One more thing: You have a comment in there "if data loading has completed," but all the work in the code you posted is going synchronously on the main thread. By the time your viewDidLoad method has completed your filePathsArray is initialized. You don't need to do anything tricky to account for a case where filePathsArray is still nil, unless you're worried about the table view loading data before the view controller's view has actually loaded. But that would be very weird.
Why are you initializing filePathsArray over and over again first under viewDidLoad and then under tableview.
This is how I would write the code.
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//initializing array and getting values the first time when page loads.
filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//return whatever the count of this array is. no need to do any if! checks
return [filePathsArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MainCell"];
}
cell.textLabel.text = [filePathsArray[indexPath.row] lastPathComponent];
return cell;
}
I'm making a note taking app for the iPad, and it lets the user draw lines, and right now, it can save the pages of the notebook by saving each page as a PNG in the documents directory. Here's the code I have to save the images:
- (IBAction)saveImage:(id)sender {
UIImage *saveImage = drawImage.image;
if (saveImage != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"%#-%d.png", #"image", numberOfPages] ];
NSData* data = UIImagePNGRepresentation(saveImage);
[data writeToFile:path atomically:YES];
}
}
Just as a side note, numberOfPages is an int that is set to add 1 each time a "new page" button is pressed, this way, each image is named "image1", "image2", etc.
So my question is: How would I set up a UITable so the user can see a list of all the pages they've made.
Thanks so much for your time,
Karl
Each time you make a new page, add a string with the image's name to an array. Then, iterate through the array to populate a UITableView. When the user selects a cell, open the file with that name.
#import "RootViewController.h"
#implementation RootViewController
#synthesize keys, names;
AppDelegate *appD;
- (void)viewDidLoad
{
[super viewDidLoad];
appD = (AppDelegate *)[[UIApplication sharedApplication] delegate];
names = appD.data;
NSArray *array = [[names allKeys] sortedArrayUsingSelector:#selector(compare:)];
keys = array;
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
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 = [appD.data objectForKey:key];
static NSString *SectionsTableIdentifier = #"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SectionsTableIdentifier];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = [nameSection objectAtIndex:row];
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSString *key = [keys objectAtIndex:section];
key = [key substringFromIndex:2];
return key;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger section = indexPath.section;
NSUInteger row = indexPath.row;
NSString *key = [keys objectAtIndex:section];
NSArray *nameSection = [appD.data objectForKey:key];
appD.theInfo.primary = [nameSection objectAtIndex:row];
[self performSegueWithIdentifier:#"secondarySegue" sender:self];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
#end
This is for a table in a navigation controller that populates itself from a .plist and moves to another table when a cell is clicked. The tableview is connected to the view controller with delegate and datasource outlets.
I load data from plist to uitableview like this:
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [[documentPaths lastObject] stringByAppendingPathComponent:#"data.plist"];
NSMutableDictionary *resultDic = [[NSMutableDictionary alloc] init];
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
NSDictionary *myDict = [NSDictionary dictionaryWithContentsOfFile:path];
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"purpleKey"])
{
NSArray *purple = [myDict objectForKey:#"Purple"];
[resultArray addObject:#"Purple"];
[resultDic setValue:purple forKey:#"Purple"];
}
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"orangeKey"])
{
NSArray *orange = [myDict objectForKey:#"Orange"];
[resultArray addObject:#"Orange"];
[resultDic setValue:orange forKey:#"Orange"];
}
self.tableData = resultDic;
self.sectionsTitle = resultArray;
}
titleForHeaderInSection
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [sectionsTitle objectAtIndex:section];
}
my plist structure
My question is:
How can I manually set title for Purple header and Orange header without to changing names in plist file?
like this: Purple = Category 1, Orange = Category 2
EDIT
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return sectionsTitle.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [sectionsTitle objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
int num = [[tableData objectForKey:[sectionsTitle objectAtIndex:section]] count];
if (num > 3) {
num = 3;
}
return num;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *dict = [[tableData objectForKey:[sectionsTitle objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.numberOfLines = 1;
cell.textLabel.font = [UIFont systemFontOfSize:11];
cell.textLabel.text = [NSString stringWithFormat:#"%# - %#", [dict objectForKey:#"Name"], [dict objectForKey:#"Address"]];
if ([dict objectForKey:#"Address"] == (NULL)) {
//do nothing
}
return cell;
}
From the look of your code, the section headers are coming from resultsArray, which you are populating with the constant strings Orange and Purple.
You can just put different constant strings into that array, unless I'm missing something.
So, instead of
[resultArray addObject:#"Orange"];
Use
[resultArray addObject:#"Category 1"];