如果@synthesize 创建了 ivar,为什么 Apple 还要创建它们?

Why is Apple creating ivars if @synthesize create them?

我无意中发现了这段来自 Apple 的代码:

@interface TiltShift : CIFilter
{
    CIImage *inputImage;
    NSNumber *inputRadius;
}
@property (retain, nonatomic) CIImage *inputImage;
@property (copy, nonatomic)   NSNumber *inputRadius;
@end

@implementation TiltShift

@synthesize inputImage;
@synthesize inputRadius;

Apple 正在创建属性,同时创建 ivar 并合成它们。我的问题是:Apple 为什么要这样做?

据我所知,即使没有 @synthesize,Xcode 也会为声明的属性创建下划线 ivar。所以,我们已经创建了 _inputImage_inputRadius,另一件奇怪的事情是,给定这段代码,Xcode 如何知道 Apple 想要将属性与不带下划线的 ivar 相关联。

我会简单地这样做:

@interface TiltShift : CIFilter
{
   //  CIImage *inputImage;
   //  NSNumber *inputRadius;
}
@property (retain, nonatomic) CIImage *inputImage;
@property (copy, nonatomic)   NSNumber *inputRadius;
@end

@implementation TiltShift

// @synthesize inputImage;
// @synthesize inputRadius;

并有下划线 ivars。

这不仅仅是 Apple。我在网上看到很多代码,来自其他开发人员,这样做,我在最近的代码中也看到了。在我看来,这是糟糕的代码,因为它无法区分 "real" ivars 和 ivars 备份属性。

创建这样的代码有意义吗?

TLDR - 这是旧代码,在 ARC 之前,在 属性 自动合成之前。我们在这里讨论的是 2011 年之前(或 2010 年?)之前的代码。

@synthesize 不会创建下划线变量。它将创建与 属性.

同名的 ivars

这就是为什么在旧代码中我们使用 @synthesize inputImage = _inputImage; 之类的东西来正确地为 ivar 添加下划线。

现代自动合成(当您根本不指定 @synthesize 时)将创建带下划线的 ivars。

您知道,历史上带下划线的变量是为 Apple 保留的,因此没有人应该使用它们。