如何在Objective C中通过表视图从NSArray中删除对象



首先,我是Objective C的新手,这是我第一次在Objective C中开发。由于某种原因,我在如何从NSArraymy tableview删除对象(其中包含对象)上遇到了困难。尝试了一些不同的东西,但似乎我有点卡住了。。。我应该在下面的代码中输入什么?

bookmarks.m

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]withRowAnimation:YES]; 
    [tableView reloadData];    
}

Bookmarks.h

#import <UIKit/UIKit.h>
#import "ShowTaskViewController.h"
#import "Bookmark.h"
@interface BookmarksViewController : UITableViewController  <UITableViewDelegate,UITableViewDataSource>
{
    NSArray *bookmarks;
}
@property (nonatomic, retain) NSArray *bookmarks;
@end

tableView不管理您的内容。你必须自己做。当用户点击删除一行时,您必须从数组中删除该项,并通知表视图删除该单元格(使用动画)。

我建议您将数据阵列更改为NSMutableArray。然后你可以这样做:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    [bookmarks removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] 
                     withRowAnimation:YES]; 
}

或者,您可以临时创建一个NSMutableArray。

NSMutableArray *mutableBookmarks = [NSMutableArray arrayWithArray:bookmarks];
[mutableBookmarks removeObjectAtIndex:indexPath.row];
self.bookmarks = [NSArray arrayWithArray:mutableBookmarks];

最新更新