Objective C multiple declarations of instance variables / properties

喜欢而已 提交于 2019-12-06 05:17:25

What you're seeing was required in earlier versions of Objective-C, but isn't any more.

In the first versions of Objective-C used by NeXT up until the new runtime was introduced (with Objective-C 2.0 on Mac OS X), all instance variables had to be declared as part of the class's structure in its @interface. The reason was that if you subclassed a class, the compiler needed to know the instance variable layout of the class so it could see at what offset to put the subclass's instance variables.

When properties were introduced, synthesized properties had to be "backed" by an instance variable in the class's structure. Therefore you had to declare both an instance variable and the property.

All of the above is no longer true. Newer Objective-C is less fragile in the way it looks up instance variable offsets, which has meant a few changes:

  • not all instance variables need to be in the @interface. They can now be defined in the @implementation: though not in categories due to the possibilities of clashing and other issues.
  • instance variables for synthesized properties can be inferred and created based on the property definition.
  • you can programmatically add instance variables to classes you're creating at runtime (only before you've registered the class as available to the system).

So, to reiterate, you only needed to declare both the instance variable and a synthesized property in older versions of the Objective-C language. What you're seeing is redundant and should not be considered a "best practice".

I tend to think of properties as my public variables as others as private however, you're right when you say "really isn't necessary".

If you omit the ivar, an ivar is still created

I create both so that all of my ivars are together and within the braces just after the interface declaration

@interface MyClass
{
    int variable1;
}
@end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!