Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properties vs. Instance Variables

I am confused as to why some classes declare a property but do not declare an ivar and vice versa.

Is it standard practice when declaring an instance variable to also declare it as a property as well?

Example:

@interface AppDelegate : NSObject <UIApplicationDelegate>
{
    UIWindow *window;
    UINavigationController *navigationController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;

is just standard practice when declaring a class's ivar to make it a property as well?

I get that the @property creates its own elongated setter (and getter with @synethesize) but why does it need to be an ivar as well?

like image 220
GPP Avatar asked Aug 18 '12 02:08

GPP


1 Answers

It doesn't.

In the old days, ivars were required to be declared in the @interface. This is actually still true for PPC and i386 (i.e. 32-bit intel) targets. This is because of the fragile base class problem, which required that all subclasses know the exact size of their superclass. As such, ivars need to be in the @interface or nobody can subclass the class.

With the move to x86_64 and ARM, alongside obj-c 2.0 came a fix for the fragile base class problem. With this fix, class sizes no longer need to be known at compile time but can be deferred to runtime. Therefore, ivars can be declared in other places. Notably, an ivar can now be synthesized from a @property (more specifically the @synthesize line in the implementation). In Clang they can also be declared in a class extension block (which looks like @interface ClassName ()) or directly on the @implementation.

Today, there are 3 reasons why you find ivars declared in @interface blocks:

  1. Old code (or programmers with old habits) that hasn't been updated to take advantage of the ability to hide ivar declarations.
  2. Code that needs to run on PPC or i386.
  3. Code that, for whatever reason, wants their ivars to be public. This should never be the case.

When writing code today that doesn't need to target the old runtime, you should either synthesize your ivars from your properties (preferred), or if you need ivars that aren't tied to properties you should declare them in a class extension or on your @implementation. The primary reason for this is because the header file documents the public API of your class and should not contain anything that's not public. Ivars are not public, and therefore should not be in the header file.

like image 110
Lily Ballard Avatar answered Oct 20 '22 06:10

Lily Ballard