i`m trying to make an NSMutableArray From NSUserDefaults so i can add/delete and edit it later
my code is
- (void)viewDidLoad {
[super viewDidLoad];
NSUserDefaults *ArrayTable = [NSUserDefaults standardUserDefaults];
[ArrayTable setObject:@"One" forKey:@"myArray"];
[ArrayTable setObject:@"Two" forKey:@"myArray"];
[ArrayTable setObject:@"Three" forKey:@"myArray"];
[ArrayTable setObject:@"Four" forKey:@"myArray"];
[ArrayTable setObject:@"Five" forKey:@"myArray"];
[ArrayTable synchronize];
NSMutableArray *array = [[NSMutableArray alloc] init];
array = [ArrayTable objectForKey:@"myArray"];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count];
}
- (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];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
cell.textLabel.text = [array objectAtIndex:indexPath.row];
return cell;
}
when i build and run nothing shows up
i googled it but with no help, i`m sure i didn’t understand how to do it
what i need is to build an app that contain a tableview with empty data, the use will fill in the data Add/Delete/Edit
can someone please explain it for me
thank you in advance
First, you assigned your array from the user defaults to a local variable named
array. Assuming you have a property for this class also namedarray, this local assignment masks that. If it had not, you would have crashed when you tried to call-counton a string.The
NSUserDefaultsobject is a dictionary. Each time you call-setObject:forKey:on it, you are actually replacing the object previously set for that key. So at the end of your series of calls to-setObject:forKey:, the resulting value is theNSStringFive.You can’t really store a mutable object in the
NSUserDefaults, instead you would take a mutable copy of the object when you assign it to your local variable or ivar. To get the behavior you are probably expecting, you should do something like the following:With that example code, it should behave the way you expected it to behave, and you can continue on. Obviously it makes no sense to set the array in
-viewDidLoadand then immediately read a mutable copy. The key thing to keep in mind is that-setObject:forKey:will always replace any object already set for that key. It doesn’t add elements or anything like that.