Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property Declaration and Automatic Backing Storage Allocation

I'm trying to understand Objective-C properties and I have some lingering questions about their syntax.

What is the difference between explicitly declaring an ivar for a property like this:

@interface myObject1 : NSObject {
  NSString *title;
}
@property (copy) NSString *title;
@end

and this:

@interface myObject2 : NSObject {
}
@property (copy) NSString *title;
@end

The myObject2 example seems to work. Is it OK to implement properties as in myObject2 or should the associated ivar always be explicitly defined?

What are the ramifications of not explicitly declaring the ivar?

like image 368
Avalanchis Avatar asked Jul 13 '10 14:07

Avalanchis


2 Answers

On the modern Objective C runtime (nonfragile-abi) they are the same, the ivar backing will be created automatically by the @synthesize declaration. This is the runtime used by iPhone, and 64 bit Mac OS X apps. 32 bit Mac OS X use the legacy runtime, where it is not possible to synthesize the ivar, and the second bit of code you wrote would not compile properly.

The most recent versions of the iPhone simulator use the modern runtime, but older ones don't. So while both code examples will work on actually iPhones (synthesizing the necessary storage), the second example will fail to compile for the simulator unless you have an up to date Xcode.

like image 157
Louis Gerbarg Avatar answered Nov 18 '22 03:11

Louis Gerbarg


With the modern runtime they are the same (as already mentioned) except for the fact that the ivars that are not explicitly defined like in MyObject1 will not show up in the debugger when you view variables or hover the mouse over variables, you have to print out the variable values or set the summary of the variable in the variables view to display the properties.

I started using the MyObject2 way of doing things because of typing less but it is more annoying having to type in the gdb command line to view the variable state in the debugger :(

like image 26
Brent Priddy Avatar answered Nov 18 '22 03:11

Brent Priddy