【问题标题】:Modern Objective-C and @synthesize现代 Objective-C 和 @synthesize
【发布时间】:2013-03-22 16:30:44
【问题描述】:

我正在尝试将我的代码转换为现代 Objective-C 风格。我如何在这里阅读http://www.techotopia.com/index.php/The_Basics_of_Modern_Objective-C": "然而,在现代 Objective-C 的情况下,默认情况下会进行合成,因此不需要使用 @synthesize 声明。使用默认属性合成时,可以使用带有下划线前缀的属性名称从代码中访问实例变量属性。”

但是,我有:

Relationship.h

@interface Relationship : NSObject <NSCoding>
//...
@property(nonatomic, weak) Person* first;
//...
@end`

OtherRelationship.h

#import "Relationship.h"

@interface OtherRelationship : Relationship

@end

OtherRelationship.m

#import "OtherRelationship.h"

@implementation OtherRelationship

@synthesize first = _first;

- (void)foo
{
NSLog(@"%@", _first);
}

它正在工作。但是当我删除

 @synthesize first = _first;

我收到“使用未声明的标识符 '_first'”错误。继承变量是否不适用于自动合成,还是我应该在其他地方寻找问题?

【问题讨论】:

  • 您的示例中没有 first 属性的声明。它是从您的 .h 中丢失还是仅从您发送的 sn-p 中丢失?
  • 我在Relationship.h中没有看到任何名为“first”的东西
  • 请注意,您可以完全删除@synthesize
  • 我的代码中第一个,我在上面更正了这个。

标签: objective-c synthesize


【解决方案1】:

超类中的支持 ivar 是子类的 @private。也就是说,子类可以调用 self.first,但不能调用 _first。如果您想再次@synthesize,请使用不同的名称,因为您不能引用 _first。例如,替换为@synthesize first = _ffirst; 或直接删除@synthesize。

【讨论】:

  • 所以我可以删除@synthesize,但我必须制作“NSLog(@"%@", self.first)"?
  • 好的,看起来不错。但是为什么我不能将@property(nonatomic, weak) Person* first; 添加到OtherRelationship 接口(这个IMO 应该首先为OtherRelationship 类创建@public)然后只删除@synthesize 并在OtherRelationship 实现中使用_first?
  • 如果子类合成了超类中已经合成的属性,则新的访问器会覆盖旧的访问器。所以你仍然在干扰超类中定义的第一个变量。
猜你喜欢
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
  • 2011-08-16
  • 2011-11-21
  • 2013-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多