In Obj-c when declaring a variable within @interface
@interface: NSObject{ MyObject* myObject}
@property (unsafe, nonatomic) MyObject* myObject;
Vs. Only declare it as a property
@interface: NSObject{}
@property (unsafe, nonatomic) MyObject* myObject; @end
Not declare any var here?
Regards Christian
A property can be backed by an instance variable, but you can also define the getter/setter to do something a bit more dynamic, e.g. you might define a lowerCase property on a string which dynamically creates the result rather than returning the value of some member variable.
The Objective-C declared properties feature provides a simple way to declare and implement an object's accessor methods.
An instance variable is a variable that exists and holds its value for the life of the object. The memory used for instance variables is allocated when the object is first created (through alloc ), and freed when the object is deallocated.
@property
defines an interface, not an implementation. In your case, you're defining a readwrite property. This means that you're promising to implement -myObject
and -setMyObject:
. This has nothing to do with ivars.
Now, the most common way to implement those methods is by having them be backed by an ivar. As a convenience, ObjC lets you automatically generate the required methods with an ivar store using @synthesize myObject=myObject_;
This says "create the required methods for the property myObject
using an automatically created ivar called myObject_
." The ivar myObject_
is a real ivar, and you can access it normally (though you generally shouldn't; you should use accessors).
Instead of using @synthesize
, you could just implement -myObject
and -setMyObject:
. You could even use @dynamic myObject;
to tell the compiler "don't worry about the implementations for this property; it'll be handled correctly at runtime."
There are a few differences between @property
and just declaring methods, but in principle, this line:
@property (nonatomic, readwrite, strong) MyObject* myObject;
is conceptually the same as this:
- (MyObject *)myObject;
- (void)setMyObject:(MyObject *)anObject;
Declaring the ivar yourself has no real impact here. You still need to implement the methods somehow. If your named ivar is the same as the ivar @synthesize
is using, then @synthesize
just won't create a new ivar.
As a matter of practice, I discourage people from declaring ivars anymore. I recommend just using public and private properties with @synthesize
to create any needed ivars. If you must have a manual ivar for some reason, then I recommend declaring them in the @implementation
block rather than the @interface
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With