0

我有一个带有按钮的主视图,当按下该按钮时,它将 Web 视图(如书签)中的 url 添加到表视图中。唯一的问题是它没有加载。我已经在这几个小时了,但无法弄清楚。我想我在表格视图中加载数据错误但不确定。

这是 MainViewController.m

- (IBAction)bookmark:(id)sender {
    UIActionSheet *actionSheet = 
        [[UIActionSheet alloc] initWithTitle:[[[[self webView] request] URL]
            absoluteString] delegate:nil cancelButtonTitle:@"Cancel"
            destructiveButtonTitle:nil  otherButtonTitles:@"Add", nil];
     [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        NSMutableArray *bookmarks = [[[NSUserDefaults standardUserDefaults]
            arrayForKey:@"Bookmarks"] mutableCopy];

        if (!bookmarks) {
            bookmarks = [[NSMutableArray alloc] init];
        }
        [bookmarks addObject:[[[[self webView]request] URL] absoluteString]];
        [[NSUserDefaults standardUserDefaults] setObject:bookmarks
            forKey:@"Bookmarks"];
    }
}

这是 BookmarksViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];

    NSLog(@"%@", bookmarks);

    bookmarks = [[[NSUserDefaults standardUserDefaults]
                  arrayForKey:@"Bookmarks"] mutableCopy];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    [[NSUserDefaults standardUserDefaults] setObject:bookmarks forKey:@"Bookmarks"];

    cell.textLabel.text = [self.bookmarks objectAtIndex:indexPath.row];
    return cell;
}
4

2 回答 2

0

当您的应用程序首次运行时,没有BookmarksNSUserDefaults. 所以这一行:

bookmarks = [[[NSUserDefaults standardUserDefaults]
              arrayForKey:@"Bookmarks"] mutableCopy];

viewDidLoad叶子bookmarks设置为nil

在您的操作表处理程序中,您实际上可以正确处理此问题。

另一个大问题是呼吁:

[[NSUserDefaults standardUserDefaults] setObject:bookmarks forKey:@"Bookmarks"];

在你的cellForRowAtIndexPath...方法中。为什么NSUserDefaults每次需要一个单元格时都要更新?不要这样做。

于 2013-09-25T23:08:19.550 回答
0

该命令[tableView dequeueReusableCellWithIdentifier:CellIdentifier]并不总是返回一个单元格。如果可重用单元队列中有一个单元,它只返回一个单元。

所以你的方法应该是:

- (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];
    }
    [[NSUserDefaults standardUserDefaults] setObject:bookmarks forKey:@"Bookmarks"];

    cell.textLabel.text = [self.bookmarks objectAtIndex:indexPath.row];
    return cell;
}
于 2013-09-25T23:11:52.503 回答