目标C - 没有@synthesize需要下划线?

时间:2014-04-22 20:12:52

标签: ios objective-c xcode

我从这个方法得到一个错误,我有一个imageView属性链接到我的故事板中的头文件,但只有当我使用_imageView而不是imageView时它才有效。原始代码使用不带下划线的imageView版本,但它在@implementation下有一个@synthesize imageView行。我是否因为缺少@synthesize而需要下划线?

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *filteredDictionary = [filterNames objectAtIndex:indexPath.row];
imageView.image = [filteredDictionary objectForKey:@"filteredImage"];

3 个答案:

答案 0 :(得分:2)

是的,苹果公司对此进行了翻转。

如果您添加默认@synthesize:

@synthesize propertyName;

然后,实例变量将被称为propertyName。如果省略@synthesize并允许隐式推断,则实例变量将被称为_propertyName

我想一个内部的思想学派最终胜过另一个。

答案 1 :(得分:1)

在当前版本的Xcode中,它会在幕后为你做@synthesize。但这样做会迫使你使用下划线。它类似于使用@synthesize imageView = _imageView。因此,如果您不合成,请使用下划线。

答案 2 :(得分:1)

访问实例变量有两种可能的变体:

  1. 使用财产。在这种情况下,您应该使用self.imageView
  2. 通过直接访问变量。访问代码取决于是否使用@synthesize 如果不使用 @synthesize,编译器会自动为您创建带有下划线的实例变量:_imageView
    如果您使用 @synthesize imageView@synthesize imageView = imageView,那么您应该通过调用imageView而不使用下划线来访问实例变量。