Displaying a plist file in a UITableView
So, my app consists of a textview in one view controller. When the user taps a save button, the text from that textview is written to a plist with this code:
- (IBAction)saveDoc:(id)sender
{ NSString *typedText = typingArea.text; NSMutableArray *totalFiles = [[NSMutableArray alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"savedFiles.plist"];
[totalFiles addObject:typedText];
[totalFiles writeToFile:path atomically:YES];
[totalFiles release];
}
Then, in a totally separate view controller, I have a UITableView tha开发者_运维知识库t displays the saved file using this code.:
- (void)viewDidLoad {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectories = [paths objectAtIndex:0];
NSString *path = [documentsDirectories stringByAppendingPathComponent:@"savedFiles.plist"];
NSLog(@"Got Path: %@", documentsDirectories);
array = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSLog(@"Loaded Array into new array: %@", array);
[super viewDidLoad];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
//self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
array is an NSMutableArray. Then I load it into the table view like this:
// Configure the cell...
NSString *cellValue = [array objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
My question is, how do I make it so I can save multiple files and show multiple files in the table view. Right now, only one file can be saved and it is overwritten every time the save button is pressed.
Thanks in advance,
Tate
My strategy is usually to make an NSDictionary and save the files with the key as the name of the file, and the object as your array. However before you do that one I think you need to check whether the current location has something inside.
To do that:
NSDictionary currentData = [NSDictionary dictionaryWithContentsOfFile:path];
[currentData setValue:totalFiles forKey:@"firstArray"];
[currentData writeToFile:path atomically:YES];
You can of course improvise yourself. Check out documentation for NSDictionary, it's a very useful data type IMO (but can get very complicated).
Otherwise why don't you just have another plist file? i.e. use savedFile.plist and savedFile2.plist or something like that?
精彩评论