This question already has an answer here:
How To Reload Dictionaries On Tableview By Segment Button Click Using Objective C?
(1 answer)
Closed 7 years ago.
I am trying to create Plist dictionary data's read and load into tableview. Here, I am maintaining two segment control button and single tableview. Whenever I selected segment control button one I need to load first plist dictionary data then button two to load second one. I need to differentiate two data set and based on button click It should reload.
My Code:
// to read data
NSArray *pathse = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = pathse.firstObject;
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"port.plist"];
savedUrl = [[NSMutableDictionary alloc] initWithContentsOfFile: plistPath];
- (IBAction)Click_Segmentbutton:(id)sender {
switch (segment_Button.selectedSegmentIndex) {
case 0:{
break;}
case 1:{
break;}
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSIndexPath *indexPath;
if (indexPath.section == 0)
{
return [[savedUrl objectForKey:#"boysinfo"] count];
}
else
{
return [[savedUrl objectForKey:#"girlsinfo"] count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//Here I need to get whenever click the tableview cell selected cell all details
}
As per my understanding to your question, below is code for your purpose.
//Global
NSMutableDictionary *savedPlistDictionary;
- (void)viewDidLoad {
//Read the plist and save in plistDictionary.
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPathString = paths.firstObject;
NSString *plistNameString = #"second.plist"; //Second plist file
NSString *plistPathString = [documentsPath stringByAppendingPathComponent:plistNameString];
plistDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile: plistPathString];
}
//Function to fetch the plist file based on index (segment selected)
- (void)saveDataWithSelectedIndex:(int)index {
if (index == 1){
savedPlistDictionary = [plistDictionary objectForKey:#"boysinfo"];
}
else {
savedPlistDictionary = [plistDictionary objectForKey:#"girlsinfo"];
}
}
- (IBAction)Click_Segmentbutton:(id)sender {
//Pass the selected index segment to function and savedPlistDictionary will be updated accordingly
switch (segment_Button.selectedSegmentIndex) {
case 0:{
[self saveDataWithSelectedIndex:0];
break;}
case 1:{
[self saveDataWithSelectedIndex:1];
break;}
}
[self.tableView reloadData]; //Reload the tableView
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [savedPlistDictionary count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//Here parse the data and load cells
}
Related
I have 2 tableviews at the moment. One is the basic which shows each cells and if selected it navigates to a detail view controller.
I created a new ViewController to create a filtered page view. I populate my page view with plist. I managed to create a filter but i don't know how to proceed from here.
This is my code:
- (IBAction)ingredientsAddButton:(UIButton *)sender
{
int j=0;
onemsiz.text=ingredientTextField.text;
ingredientText=onemsiz.text;
NSLog(ingredientText);
NSString *path = [[NSBundle mainBundle] pathForResource:#"recipes" ofType:#"plist"];
NSArray *arrayOfPlist = [[NSArray alloc] initWithContentsOfFile:path];
if (arrayOfPlist==NULL) {
}else {
for (int i=0; i<4; i++) {
// i currently have 4 element is plist.
NSString *strCurrentRecipeIngredients = [[arrayOfPlist objectAtIndex:i] objectForKey:#"recipeIngredients"];
NSString *strCurrentRecipeName = [[arrayOfPlist objectAtIndex:i] objectForKey:#"recipeName"];
//NSLog(#"%d. Loop \n", i+1);
if([strCurrentRecipeIngredients rangeOfString:(#"%#",ingredientText)].location!=NSNotFound)
{
NSLog(#"%# contains %# ",strCurrentRecipeName, ingredientText);
NSLog(ingredientText);
NSLog(strCurrentRecipeIngredients);
j++;
}else {
NSLog(#"Not found");
NSLog(ingredientText);
NSLog(strCurrentRecipeIngredients);
}
if (ingredientText==NULL) {
NSLog(#"empty input");
}else {
}
}
}
NSLog(#"%d",j);
}
My first problem is how can I show the results in a table view? I can give some screenshots if you want.
You can add bool ivar which will tell when you need to show the filtered array and new array which will show filtered data:
BOOL isShowFilteredData;
NSArray *filteredData;
In init or viewDidLoad initialize bool to false (you don't want to show all data);
isShowFilteredData = NO;
You have to change the datasource/delegate method to use right data:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return isShowFilteredData ? isShowFilteredData.count : myDataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//configure cell, etc..
//your code
if (isShowFilteredData)
{
// show filtered data
id obj = filteredData[indexPath.row];
// do something with result
}
else
{
// show all data
}
}
Now when you want to show filtered data just change ivar to true, initialise filteredData array and fill it in with the data you want to show and call reloadData:
isShowFilteredData = YES;
filteredData = [[NSArray alloc] initWithObjects:.....];
[self.tableView reloadData];
but if you want to show all data do:
isShowFilteredData = NO;
[self.tableView reloadData];
This is just one of the solution you can use.
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 am trying to load a plist from my project, this was working until I accidentally deleted my plist. the plist has 5 arrays, with 2 elements apiece. I know that I the program is trying to access beyond the range of the array, but what I don't know is where this index is set? Here is the code that it bombs on: this code is executed twice successfully,then for some reason it tries to access it a third time and bombs on the first line,why?
It throws this exception:
NSRangeException -[_NSCFARRAY objectAtIndex] index(2) beyond bounds (2)
please help, this is for a final project due on Monday and now I feel like I have to start over again.
NSString *nameOfAccount = [account objectAtIndex:indexPath.row];
cell.textLabel.text = nameOfAccount;
NSString *accountNumber = [number objectAtIndex:indexPath.row];
cell.detailTextLabel.text = accountNumber;
Since you are displaying the data in same cell, you can include both name and number of account into a dictionary or a custom model object which will hold both info.
In your plist this might be the structure, array of dictionary objects
When you are displaying the info. For the dataSource create an array say accounts.
#define kAccountName #"Name"
#define kAccountNumber #"Number"
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *filePath = [[NSBundle mainBundle]pathForResource:#"Accounts" ofType:#"plist"];
self.accounts = [NSArray arrayWithContentsOfFile:filePath];
}
#pragma mark - Table view data source
- (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 [self.accounts count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSDictionary *account = self.accounts[indexPath.row];
cell.textLabel.text = account[kAccountName];
cell.detailTextLabel.text = account[kAccountNumber];
// Configure the cell...
return cell;
}
Source code
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'm developing an app for iPhone but I've a problem...
I've a view with some textField and the informations writed in them are saved in a plist file. With #class and #import declarations I import this view controller in another controller that manage a table view.
The code I've just wrote appear to be right but my table is filled up with 3 same row...
I don't know why the row are 3...
Can anyone help me?
This is the code for add info:
#implementation AddWishController
#synthesize titleField, linkField, descField;
-(NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:plistPath];
}
-(IBAction)done {
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:titleField.text];
[array addObject:linkField.text];
[array addObject:descField.text];
[array writeToFile:[self dataFilePath] atomically:YES];
[array release];
[self dismissModalViewControllerAnimated:YES];
}
And this control the table:
#import "WishlistController.h"
#import "AddWishController.h"
#implementation WishlistController
#synthesize lista;
-(IBAction)newWish {
AddWishController *add = [[AddWishController alloc] initWithNibName:#"AddWish" bundle:nil];
[self.navigationController presentModalViewController:add animated:YES];
[add release];
}
-(NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:plistPath];
}
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *data = [[NSArray alloc] initWithContentsOfFile:[self dataFilePath]];
return [data count];
[data release];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
cell.textLabel.text = [array objectAtIndex:0];
cell.detailTextLabel.text = [array objectAtIndex:2];
NSLog(#"%#", array);
}
return cell;
}
Your first problem is that NSArray writeToFile: doesn't append to an existing file. It just writes the complete contents of the array to the file. If a file by the same name already exist, then the function overwrites it.
This means that in your code at present, you only ever save an array with three elements. No matter how many times the user saves in the AddWishController's view, only the last three pieces of information captured are ever preserved on disk.
Secondly, your WishlistController is misconfigured.
This:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *data = [[NSArray alloc] initWithContentsOfFile:[self dataFilePath]];
return [data count];
[data release];
}
Will always return a count of three because the array in the file always has three elements. However, even that is wrong because you don't want to display each element in separate cell. Your cellForRowAtIndexPath: very clearly puts the first and last elements of the array into each and every cell.
At the very least here, you need a two-dimensional array. Better yet you need an array of dictionaries. Each dictionary will hold the results of one "done" operation in -[AddWishController done]. Put add each dictionary to an array. Then in your tableview controller, return the count of the array for the number of rows in the table. Then in cellForRowAtIndexPath: you should get the dictionary in array element of indexpath.row. Then get the text for the cell UI elements from each entry in the dictionary.
Usually, you also would not save to file until the app quits. Instead, put the array in an property of the app delegate. In AddWishController create a property to refers to the app delegates property. Do the same in the tableview controller. Now you can populate the array in the first controller and read it from the second.
Basically, you need to start over from scratch.
In WishController# load, you put three different items into the Array, So of course, if in WishlistController# tableView: numberOfRowsInSection: you return [data count] as the number of rows, you get three rows.
On the other Hand, you in WishlistController# tableView: cellForRowAtIndexPath: you do not look, which entry should be presented, so it will always show only the one and only cell.
If you want to present only one cell in your table, you replace your WishlistController# tableView: numberOfRowsInSection: with
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
If you want to show multiple Wishes, you better make a real object of it, or at least use NSDictionary, where one entry in the Dictionary represents one object (=Wish) with multiple attributes (title, link, desc).
If for your first steps in Cocoa/Objective-C you really really want not to look into NSDictionary yet, you could also
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return floor([data count]/3);
}
and then in #tableView: cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
...
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
int row = indexPath.row * 3;
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
cell.textLabel.text = [array objectAtIndex:row];
cell.detailTextLabel.text = [array objectAtIndex:row+2];
NSLog(#"%#", array);
}
return cell;
}
But this definitly is only for prototyping-to-get-something-displayed. You soon want to look into NSDictionary and before releasing anything, you better learn the use of proper objects for your Data Model, for instance with Core Data. Really.
two more things:
-In WishlistController#tableView:numberOfRowsInSection: the line
[data release];
after the return never gets called. You probably want to
[data autorelease];
before the return-statement.
- You do not want to read a file // look for your objects each time a row in your table gets displayed. Create an array as an instance-variable of your controller and use it as your datasource.