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
@propertydefines an interface, not an implementation. In your case, you’re defining a readwrite property. This means that you’re promising to implement-myObjectand-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 propertymyObjectusing an automatically created ivar calledmyObject_.” The ivarmyObject_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-myObjectand-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
@propertyand just declaring methods, but in principle, this line:is conceptually the same as this:
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
@synthesizeis using, then@synthesizejust 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
@synthesizeto create any needed ivars. If you must have a manual ivar for some reason, then I recommend declaring them in the@implementationblock rather than the@interface.