AndrewSB
AndrewSB

Reputation: 951

Plist for persistent data in UITableView between launches

I have this plist, called sleeps.plist in my main directory. It looks like enter image description here

I want to put it's contents into a UITableView... So I subclassed a ViewController with a TableView and I set it as the data source and delegate.

I've made it so that anything in the NSArray 'sleeps' gets added to the Table (tested out with static data).

Now, I want to be able to add data from this plist so the data (if a user enters more) stays persistent between launches.

Here's the code I put in my viewDidLoad of my ViewController subclass.

NSString *path = [[NSBundle mainBundle] pathForResource:@"sleeps" ofType:@"plist"];
NSDictionary *myDict = [[NSDictionary alloc] initWithContentsOfFile:path];

NSArray *myArray = [myDict objectForKey:@"Root"];
sleeps = [myArray copy]; //sleeps is an NSArray declared right after the @implementation line

NSLog(@"reached point");

NSLog(@"%@", sleeps);

It logs reached point, and then null... So I'm not sure what I'm doing wrong. Also, the table is empty. Can somebody point me in the right direction?

Upvotes: 0

Views: 48

Answers (2)

rmaddy
rmaddy

Reputation: 318884

Since your plist root is an array and not a dictionary, your code should be:

NSString *path = [[NSBundle mainBundle] pathForResource:@"sleeps" ofType:@"plist"];
NSArray *myArray = [[NSArray alloc] initWithContentsOfFile:path];

sleeps = [myArray copy]; //sleeps is an NSArray declared right after the @implementation line

NSLog(@"reached point");

NSLog(@"%@", sleeps);

If you want the user to be able to add values then sleeps should be an NSMutableArray and you should call [myArray mutableCopy].

But if you want to persist the additional data then you need to write the array to a writable folder such as the Documents folder.

Upvotes: 1

David Berry
David Berry

Reputation: 41236

"Root" as a key doesn't really exist, you have a plist containing an array of dictionaries, all you need is:

sleeps = [[NSArray alloc] initWithContentsOfFile:path];

Upvotes: 1

Related Questions