为什么Xcode要求在一个NSMutableArray变量名称前加下划线?

非生物 发布于 2014年04月26日
无人欣赏。

关键代码如下:


@interface XYZToDoListTableViewController ()
@property NSMutableArray *toDoItems;
@end
@implementation XYZToDoListTableViewController
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        [_toDoItems removeObjectAtIndex: indexPath.row];
        //        [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
        //                         withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath]
                         withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView reloadData];
    }
}
这里要实现一个TableView的删除功能,我在第14行写上
[toDoItems removeObjectAtIndex: indexPath.row];
Xcode会报错,并提示我改成_toDoItems。 改成了_toDoItems能实现功能,但是为什么要加下划线在下面呢?

共6条回复
董一凡 回复于 2014年04月26日

toDoItemsproperty,你要引用他必须是self.toDoItems,至于下划线的话,是编译器会自动生成并把toDoItems绑定到一个你看不到的变量_toDoItems,你需要搞明白property是什么。尤其在没有ARC之前,提示:systhesize

非生物 回复于 2014年04月26日

1楼 @董一凡 改成

[self.toDoItems removeObjectAtIndex: indexPath.row];
也能运行成功。PS:我基础比较薄弱,所以问出这样的问题,见笑了。同时回答让我知道了ARC和synthesize这两个词。

董一凡 回复于 2014年04月26日

2楼 @非生物 谁都有不知道东西,这个正常得很。你要是趁这个机会把这个问题搞明白。那收获就会更大了。

Edision 回复于 2014年04月27日

我想说你是在工作还是在学习阶段阿?

happyming 回复于 2014年04月27日

[self.toDoItems removeObjectAtIndex: indexPath.row]; 还是写成 self->_toDoItems的比较好 我个人觉得

@property NSMutableArray *toDoItems; 真正的代码应该是@property NSMutableArray *toDoItems = _toDoItems;

非生物 回复于 2014年04月27日

4楼 @Edision 这个是Xcode 的 Developer Library 里面的 Start Developing iOS Apps Today 所讲的 toDolists 的App。我现在在做的是添加删除功能。

登录 或者 注册
相关帖子