Leon
Leon

Reputation: 417

fill tableview with mutable array

i've got a nsmutablearray which is filled by the user:

NSString *_string = _text.text;
[_array addObject:_string];
[self saveIt];
_text.text = @"";

_text is a textField, _array is a nsmutablearray

then i've got a method which saves the string in the nsuserdefaults:

-(void)saveIt {

NSUserDefaults *tableDefaults = [NSUserDefaults standardUserDefaults];
[tableDefaults setObject:_array forKey:@"key"];

}

well, how can i display the saved array in the tableview when the app is opened again ?

thanks :)

Upvotes: 1

Views: 4599

Answers (1)

Anomie
Anomie

Reputation: 94794

You load the array back out of NSUserDefaults, and use the array's contents to return the appropriate values from the various methods of the table view's data source, particularly tableView:numberOfRowsInSection: and tableView:cellForRowAtIndexPath:.


Quick example:

First, read the array back out of NSUserDefaults at some point, probably in your class's init or in application:didFinishLaunchingWithOptions: (after calling NSUserDefaults's registerDefaults:, of course):

_array = [[NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] arrayForKey:@"key"]] retain];

Then use it for the mentioned methods:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"] autorelease];
    }
    cell.textLabel.text = [_array objectAtIndex:indexPath.row];
    return cell;
}

That should get you started. You'll probably also want to call reloadData or insertRowsAtIndexPaths:withRowAnimation: on your table view when adding something to the array, see the documentation for details.

Upvotes: 2

Related Questions