【问题标题】:fill tableview with mutable array用可变数组填充 tableview
【发布时间】:2011-03-19 21:44:56
【问题描述】:

我有一个由用户填充的 nsmutablearray:

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 中显示保存的数组?

谢谢:)

【问题讨论】:

    标签: objective-c uitableview ios4 nsmutablearray nsuserdefaults


    【解决方案1】:

    您从 NSUserDefaults 中加载回数组,并使用数组的内容从表视图的 data source 的各种方法中返回适当的值,特别是 tableView:numberOfRowsInSection:tableView:cellForRowAtIndexPath:


    快速示例:

    首先,在某个时间点从 NSUserDefaults 中读回数组,可能是在你的类的 init 或 application:didFinishLaunchingWithOptions: 中(当然是在调用 NSUserDefaults 的 registerDefaults: 之后):

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

    然后将其用于上述方法:

    - (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;
    }
    

    这应该让你开始。在向数组添加内容时,您可能还想在表格视图上调用 reloadDatainsertRowsAtIndexPaths:withRowAnimation:,有关详细信息,请参阅 the documentation

    【讨论】:

    • 你能给我一个例子吗? :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多