Objective c 用可变数组填充tableview
我有一个nsmutablearray,由用户填充:Objective c 用可变数组填充tableview,objective-c,uitableview,ios4,nsmutablearray,nsuserdefaults,Objective C,Uitableview,Ios4,Nsmutablearray,Nsuserdefaults,我有一个nsmutablearray,由用户填充: NSString *_string = _text.text; [_array addObject:_string]; [self saveIt]; _text.text = @""; _text是一个textField,_array是一个nsmutablearray 然后我得到了一个方法,它将字符串保存在nsuserdefaults中: -(void)saveIt { NSUserDefaults *tableDefaults = [NS
NSString *_string = _text.text;
[_array addObject:_string];
[self saveIt];
_text.text = @"";
_text是一个textField,_array是一个nsmutablearray
然后我得到了一个方法,它将字符串保存在nsuserdefaults中:
-(void)saveIt {
NSUserDefaults *tableDefaults = [NSUserDefaults standardUserDefaults];
[tableDefaults setObject:_array forKey:@"key"];
}
那么,当再次打开应用程序时,如何在tableview中显示保存的数组
谢谢:)您从NSUserDefaults中加载数组,并使用数组的内容从表视图的各种方法返回适当的值,特别是
tableView:numberofrowsin节:
和tableView:cellForRowAtIndexPath:
快速示例: 首先,在某个时候从NSUserDefaults中读回数组,可能是在类的init或
应用程序:didFinishLaunchingWithOptions:
(当然,在调用NSUserDefaults的registerDefaults:
之后):
然后将其用于上述方法:
- (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;
}
这应该让你开始。在向数组添加内容时,您可能还需要在表视图上调用
reloadData
或insertRowsAtIndexPaths:withRowAnimation:
,有关详细信息,请参见。您能给我举个例子吗?:)
- (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;
}