I read from plist file and add data to tableview
My plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<dict>
<key>Title</key>
<string>Section1</string>
<key>Rows</key>
<array>
<string>Section1 Item1</string>
<string>Section1 Item2</string>
</array>
</dict>
<dict>
<key>Title</key>
<string>Section2</string>
<key>Rows</key>
<array>
<string>Section2 Item1</string>
<string>Section2 Item2</string>
</array>
</dict>
</array>
</plist>
.h
#import "RootViewController.h"
@interface RootViewController ()
@property (copy, nonatomic) NSArray* tableData;
@end
.m
@implementation RootViewController
@synthesize tableData;
- (void) dealloc
{
self.tableData = nil;
[super dealloc];
}
- (void) viewDidLoad
{
[super viewDidLoad];
self.tableData = [NSArray arrayWithContentsOfFile: [[NSBundle mainBundle] pathForResource: @"Table" ofType: @"plist"]];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
return [tableData count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
return [[[tableData objectAtIndex: section] objectForKey: @"Rows"] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
{
return [[tableData objectAtIndex: section] objectForKey: @"Title"];
}
- (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] autorelease];
}
cell.textLabel.text = [[[tableData objectAtIndex: indexPath.section] objectForKey: @"Rows"] objectAtIndex: indexPath.row];
return cell;
}
@end
How can I write to that strings and arrays each time a new data rather than replace the old one?
With this code you read the plist file:
and with this you write:
if you don’t want to add more items just add to
self.tableDataand when you write to file it will be added to the plist.The only problem is that you`l need to write on documents directory not on bundle.
the bundle is your app folder, signed and approved by appstore. to edit a file that was on your bundle you should copy it first and then use the copy, like this:
at the end of this code
pathis the path to a plist file on documents directory that will be exactly the same ofTable.pliston your bundle.this file at
pathyou can write and read, the file at[[NSBundle mainBundle] pathForResource: @"Table" ofType: @"plist"]you can only read.EDIT
Basically you`l need to do something like this:
https://gist.github.com/3090009
this is a helper class to work with file paths, if you have questions just ask