Bad_APPZ
Bad_APPZ

Reputation: 432

Using NSUserDefaults to load data depending on which table view cell is pressed

I want my app to work just like the 'contacts' app on iOS. When a user selects a certain TableViewCell, i want to load certain data.

enter image description here

No Matter which cell is pressed, Either "Joseph, Richard, or Shannon", This view comes up:

enter image description here

enter image description here

Both of the views look the exact same, but they just display different information. So i guess my question is: How can I programmatically set a key @"cell1" @"cell2", etc... for each cell using NSUserDefaults? But here is the catch, I dont know how many cells will be added, so i cant hard code this, How can I create a key for each table view cell for how ever many is added? Thanks for the help!

Upvotes: 0

Views: 243

Answers (3)

Asif Mujteba
Asif Mujteba

Reputation: 4656

You can do that by creating an NSMutableDictionary which stores key/value pairs for each cell than storing it in NSUserDefaults

NSMutableDictionay *dict = [[NSMutableDictionary alloc] init];
[[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"myKey"];
[dict release];

than you can update the dictionary with cell values whenever you want:

NSMutableDictionary *dict = [[NSUserDefaults standardUserDefaults] objectForKey:@"myKey"];
[dict setValue:aNameforThisCell forKey:[NSString stringWithFormat@"cell%d", indexPath.row]];

Upvotes: 0

msgambel
msgambel

Reputation: 7340

If you have your heart stuck on using NSUserDefaults, try this:

NSUserDefaults * prefs = [NSUserDefaults standardUserDefaults];
cellNumber = [prefs objectForKey:[NSString stringWithFormat:@"cell%d", index]];

You can then save the max index so that you know exactly how many UITableViewCells you will have to display.

Keep in ming that there is a low storage limit for NSUserDefaults, so you may not be able to store all of your information there. You can find out more details here.

Hope that Helps!

Upvotes: 2

Aditya Vaidyam
Aditya Vaidyam

Reputation: 6267

Perhaps you don't want to use NSUserDefaults.... that's only used for persistant user information, such as preferences. It'd be better to use Core Data for that sort of thing.

One idea, since you want to tag the views, is to use the -[UIView setTag:] or UIView.tag property/method on the UITableViewCell during cell dequeueing. Using the UITableView delegate methods, you could detect a tap on the cell, retrieve its tag, and look up the NSUserDefaults, or better, your database.

The preferred way, is to keep an indexed database, dequeue a cell, and when it's tapped, navigate to the detail pane using the cell's index. This is a far more representative programming model, than tagging a view and using NSUserDefaults to pull the data.

Upvotes: 1

Related Questions