Objective-c interface - variable declaration vs only property?

In Obj-c, when declaring a variable inside @interface

@interface: NSObject {MyObject * myObject}

@property (unsafe, non-atomic) MyObject * myObject;

Vs. Just declare it as a property

@interface: NSObject {}

@property (unsafe, non-atomic) MyObject * myObject; @end

Do not declare any var here?

Christian Relations

+7
source share
2 answers

@property defines an interface, not an implementation. In your case, you define the readwrite property. This means that you promise to implement -myObject and -setMyObject: This has nothing to do with ivars.

Now the most common way to implement these methods is to provide them with ivar support. As a convenience, ObjC allows you to automatically generate the necessary methods with the ivar repository using @synthesize myObject=myObject_; This says: "Create the necessary methods for the myObject property using an automatically generated ivar called myObject_ ." Ivar myObject_ is a real ivar, and you can access it in normal mode (although you usually shouldn't, you should use accessors).

Instead of using @synthesize you can simply implement -myObject and -setMyObject: You can even use @dynamic myObject; to tell the compiler: "Don't worry about implementations of this property, it will be correctly processed at runtime."

There are a few differences between @property and just method declaration, but basically this line:

 @property (nonatomic, readwrite, strong) MyObject* myObject; 

conceptually coincides with this:

 - (MyObject *)myObject; - (void)setMyObject:(MyObject *)anObject; 

The ivar declaration itself has no real impact here. You should still implement the methods somehow. If your named ivar matches using ivar @synthesize , then @synthesize just won't create a new ivar.

In practice, I discourage people from declaring Ivars. I recommend using only public and private properties with @synthesize to create any necessary ivars. If for some reason you should have a manual ivar, I recommend declaring them in the @implementation block rather than in the @interface .

+10
source

Skipping an ivar declaration is perfectly fine - but you wonโ€™t be able to see the ivar value in the Xcode IDE. One day, Apple can fix it.

You can "po" ivar check it in GDB or lldb.

+9
source

All Articles