开发者

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];
开发者_如何学JAVA_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 :)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜