Objective-C 101: dot notation and object properties - objective-c

I have a very basic question regarding properties in Objective-C.
I can only access object's properties via dot notation (Obj.MyProp) if I #synthesize myProp. Is that correct?
Would it be true to say that if I use my own setter method, I will no longer be able to refer to property in dot notation?
Basically I am looking for C# type of functionality where I can write my own custom getter/setter and yet provide an additional code which I need to execute when the property is set.

#property creates automatic message declarations, just like writing
(int)thing;
(void)setThing:(int)value;
#synthesize automatically creates the implementations, i.e.
(int)thing {
return thing;
}
(void)setThing:(int)value {
thing = value;
}
If you give a definition yourself, it overrides the #synthesized version. So as long as you name a method correctly, it will work, with or without #synthesize in there.
Dot notation works with either synthesized or custom method implementations.

This is not correct. You can still use dot-notation even if you write custom getters or setters provided of course that your getters and setters maintain the correct method naming for the property.

From the docs:
#synthesize
You use the #synthesize keyword to tell the compiler that it should
synthesize the setter and/or getter
methods for the property if you do not
supply them within the #implementation
block.
It only synthesizes if you haven't already written them. If you've written them, they don't get synthesized.

Related

Modern Objective-C (2013) and declaring ivars/using #property, #dynamic, and #synthesize

With the current version of Objective-C, what are the official standards and best practices for declaring ivars, using #property and #synthesize? There are a lot of posts and resources on the topic but most of them are fairly antiquated from a year or two ago. I recently learned to only declare ivars in a statement block in the implementation of a class so that the encapsulation principles of OOP aren't broken but is declaring ivars even necessary in this day and age? What would be a possible use case where doing:
#interface MyClass()
#property (nonatomic) NSString* data;
#end
#implementation MyClass{
#private
NSString* _data;
}
#end
is necessary? To further that, is it ever necessary to use #synthesize? My understanding is that using #property will auto-synthesize both the accessor methods as well as the backing ivars. I've done some experimentation and I noticed that when I don't declare NSString* _data', I can still access_data' in my class implementation. Does that mean that declaring ivars come down to a matter of style, up to the discretion of the programmer? Could I condense my code and remove all ivar declarations in the statement blocks in my implementation and just use #property in my private interface? If that's not the case, what are the advantages and disadvantages of explicitly declaring ivars?
Finally, #dynamic. From what I can gather, it's used to say to the compiler, "Hey compiler, don't auto-generate the accessor method and don't worry if you don't find an implementation for it, I'll provide one at runtime". Is that all #dynamic is used for or is there more to it?
I just want to clarify all these things because it seems like there's a lot of different opinions and that there's not necessarily one right answer. Plus as Objective-C grows and progresses, those answers will change so it'll be nice to have a concise and up-to-date guide. Thanks everyone!
(Also if there's anything that I could word better or make clearer, let me know)
EDIT:
In summary, what I'm asking is this:
1) Is declaring ivars with modern Objective-C necessary?
2) Can I achieve the same effects of declaring ivars and corresponding properties by just using #property?
3) What is #dynamic used for?
4) Can I completely forgo the use of #synthesize or is there a good use case for it?
Upvote and down vote as you see fit.
There's a lot to answer here. I'll break it down:
Declaring ivars
As you've correctly noted, modern versions of the compiler will synthesize backing instance variables for declared #properties. The exception to this is on 32-bit Macs, where the modern Objective-C runtime, including non-fragile instance variables, is not available. Assuming your application is not targeting 32-bit OS X, you don't need to explicitly declare the backing ivar for an #property.
If you still want to use an ivar directly, without a corresponding #property (something I consider a bad idea most of the time), you of course must still explicitly declare the ivar.
#dynamic
#dynamic is as you've said meant to tell the compiler "don't synthesize accessors for this property, I'll do it myself at runtime". It's not used all that often. One place it is used is in NSManagedObject subclasses, where if you declare a modeled property in the header, you don't want to compiler to complain that there's no implementation of accessors for that property, nor do you want it to generate accessors itself. NSManagedObject generates accessors for modeled properties at runtime. The story is similar for custom CALayer subclasses.
#synthesize
#synthesize explicitly tells the compiler to synthesize accessor methods, and (on iOS and 64-bit Mac) a corresponding ivar for the specified property. There are three main cases where you still need to use it:
32-bit Mac apps.
If you've written your own custom setter and getter (or just getter for readonly properties). In this case, the compiler won't synthesize accessors because it sees yours. However, it also won't synthesize the backing ivar. So, you must use #synthesize someProperty = _someProperty;, to tell the compiler to synthesize an ivar. It still won't synthesize accessor methods of course. Alternatively, you can explicitly declare a backing ivar. I favor using #synthesize in this case.
If you want to use a different name for the property's backing ivar than the default (property name with an added underscore prefix). This is rare. The main case I can think of for using it is when transitioning existing, older code, that includes direct ivar access and where the ivars are not underscore-prefixed.
Best current practice seems to be to use properties for all ivars placing the property either in the .h file if they are to be exposed and in the .m file in a class extension if local to the class.
No #synthesize is needed unless the ivar needs to be different than the underscore prepended property name.
Yes, #dynamic is as you describe.
Further, it is no longer necessary to declare local instance methods or order such that the method is above the use.
First off, #synthesize is gone for these scenarios: do not have to do it any more.
Secondly, you don't need the private ivar anymore either.
So in essence, you can just do properties.
The way of controlling access is the same idiom that had become popular before MOC dropped: put the property in the public interface as readonly and then make a readwrite version in the private interface (which should be, as you show above, merely the name with open and close parens).
Note also, that many of the things that cluttered up the public interface in the past can now ONLY be in the private interface, so for instance IBOutlets, etc., since the controller is going to be the only thing diddling them.
I never see #dynamic used anywhere except in CoreDate-generated entities.
For someone who first worked with C++ where the dream was always that the header/interface merely show the user of the class what they needed and all other details would be hidden, I think MOC (Modern Objective C) is a dream come true.
BTW, highly recommend the intro session from WWDC Modern Objective C (from 2012) and the one this year was great too.

Objective-C: Understanding Properties

So here's what I know about properties in Objective-C. Please correct me if these are not facts.
When declaring a property you are declaring the setter/getter for a instance variable
If you want to have the setter and getters defined you need to synthesize them
If you synthesize, the instance variable is defined for you. Best practice is to rename the iVar so that the getter and iVar aren't the same name. So you usually do:
#synthesize myVar = _myVar
All of my knowledge about properties is coupled with instance variables. I've watched some videos recently that say properties can be used for other instance methods besides setters/getters.
Is this true? If so, how and why would you use a property in this way? For instance I was watching a Stanford cs193p video about protocols and it said that you could have a prototype in a protocol. I could of misunderstood.
Anyways thanks to those who respond
When declaring a property you are declaring the setter/getter for a instance variable
No, you are declaring a getter and possibly a setter of a property. Period. Declaring a property does not itself imply an instance variable. There are many ways to implement a property. Instance variables happen to be a common and popular way, but non-ivar properties are very common.
If you want to have the setter and getters defined you need to synthesize them
No. (As sergio points out, I originally confused "defined" and "declared.") Almost. The #property line itself declares the setter and getter. If you want to have the setter and getter implemented for you, that is called "synthesize," but you no longer need to do this manually. The complier will automatically create a getter and setter for any property that you declare but do not implement (unless you explicitly ask it not to using #dynamic).
If you synthesize, the instance variable is defined for you. Best practice is to rename the iVar so that the getter and iVar aren't the same name. So you usually do: #synthesize myVar = _myVar
Almost. This was true a few months ago, but you no longer need to actually do that #synthesize. It will be done automatically for you by the compiler now.
This header:
#interface MyObject : NSObject
#property (nonatomic, readwrite, strong) NSString *something;
#end
is almost the same as this header:
#interface MyObject : NSObject
- (NSString *)something;
- (void)setSomething:(NSString *)something;
#end
There are some very small differences between these two, some related to the runtime and some related to the compiler, but it is clearer if you just pretend they're identical.
All you're doing in both of these cases is declaring some methods. You are not declaring how they're implemented. You're not declaring ivars. You're just declaring methods. You are now free to implement those methods any way you like. If you like, you can implement them by letting the compiler synthesize some default implementations for you. If you like you can implement them by hand. You can do one of each if you like.
Properties are synthesized by default since Xcode 4.4. So you only need to declare the property (myVar).
There will also be a _myVar available that you may use instead of accessing self.myVar.
Using a properties as a parameterless methods is torsion them into a something they are not.

Will the compiler auto-synthesize an ivar for a property declared in a category?

Before so-called "Modern Objective-C", when creating a new property in category, we needed to implement setter and getter methods. Now, we don't have to do #synthesize; the compiler will automatically create the methods and an instance variable.
But normally, we cannot add instance variables to a category, so what happens if we add a new property in a category with modern Objective-C? Does the compiler create an ivar for us?
You can declare a property in a category, which is equivalent to declaring the getter and (if readwrite) setter selectors.
The compiler will not automatically synthesize the getter and setter methods in your category implementation. If you don't explicitly define them in the category implementation, the compiler will issue a warning. You can use #dynamic in the category implementation to suppress the warning. You cannot use #synthesize in the category implementation; the compiler will issue an error if you try.
The compiler will not add an instance variable for a property declared in a category. You cannot explicitly add instance variables in a category, and you can't trick the compiler into doing it using a property.
I tested my claims using Xcode 4.5.1 targetting iOS 6.0.
Actually I don't know when we were able to add property in categories.
From Apple Docs:
A category allows you to add methods to an existing class—even to one for which you do not have the source.
and
Class extensions are like anonymous categories, except that the methods they declare must be implemented in the main #implementation block for the corresponding class. Using the Clang/LLVM 2.0 compiler, you can also declare properties and instance variables in a class extension.
and this method is used to add storage to an object without modifying the class declaration (in case you couldn't modify or don't have access to source codes of class)
Associative references, available starting in OS X v10.6, simulate the addition of object instance variables to an existing class. Using associative references, you can add storage to an object without modifying the class declaration. This may be useful if you do not have access to the source code for the class, or if for binary-compatibility reasons you cannot alter the layout of the object.
So your question for me seems to be incorrect.
Source: Apple Docs - The Objective-C Programming Language
As others have said, the way to do this is with Associative References. They are implemented much like CALayer's value / key-pair paradigm.. in that basically.. you can "associate" anything, with any "property", or "thing"…
So in your category header… if all you want to do is read a value…
#property (readonly) NSString *uniqueID;
and then write your getter…
- (NSString*) uniqueID { return #"You're not special"; }
But say.. you can't just come up with the value from within your getter.. and you need storage for either an external setter… or the class' own implementation to use… you HAVE to write a setter like...
- (void) setUniqueID:(NSString*)uId
It need not be public, necessarily… but this is where the "magic" happens.
…
[self setAssociatedValue:uId forKey:#"yourInternalStorageName"
policy:OBJC_ASSOCIATION_RETAIN_NONATOMIC];
I realized after looking at this, that I'm using some "personal categories" to help ease the setting and getting etc. of these values.. so I've posted them to this gist, as they are VERY useful.. and include such little gems as…
- (id) associatedValueForKey:(NSString*)key
orSetTo:(id)anObject
policy:(objc_AssociationPolicy) policy;
The secret to "getting it" is the "policy" portion.. These values…
OBJC_ASSOCIATION_ASSIGN = 0,
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,
OBJC_ASSOCIATION_COPY_NONATOMIC = 3,
OBJC_ASSOCIATION_RETAIN = 01401,
OBJC_ASSOCIATION_COPY = 01403
capture the same "personality" traits as are expressed when describing your properties in a "normal" declaration. You must tell the compiler how to "store" your values with those same rules, and you'll be good to go.

How does dot syntax work without explicit #property in Objective-C?

I wrote a setter and getter method following Apple's conventions and noticed that despite having no variable I can still access the setter and getter using the dot syntax. Is this normal behavior? What enables this feature?
Example:
// Header definition. Keep in mind there is no class variable or #property for height.
- (void)setHeight:(float)height;
- (float)height;
// else using the dot syntax.
object.height = 10.0f;
A property-access expression is equivalent to a message expression:
[object setTexture:tex];
A property declaration is equivalent to one (readonly) or two (readwrite/default) instance-method declarations. Keywords like retain tell the compiler how to implement the method if you tell it to do so (#synthesize).
However, you can skip the property declaration and declare the methods directly, as shown in your question. You can't synthesize their implementations, since you need a property declaration for that (otherwise, it wouldn't know what memory-management policy to use: assign, retain, or copy), but you can always implement the methods yourself.
Then, even though you declared and implemented the methods yourself, since property-access syntax and message syntax are equivalent to each other, you can use the methods whichever way you want: With a message expression, or with a property-access expression.
Some would consider it bad form, though, to use property access expressions on anything but a formal #property (e.g., myString.length or myArray.count or myView.frame). It definitely is bad form to use a property-access expression to send a message that doesn't access any kind of property; foo.retain.autorelease, for example, is bad and wrong: It reeks of trying to pretend you're programming some other language than Objective-C.
Incidentally, a property and a variable are unrelated. A #property will ordinarily be backed by an instance variable, but this is not required: You could store the property's value inside another object, or convert it to and from some other format, or both. Likewise, accessing a property (which is an accessor message) and accessing an instance variable (which is just accessing a variable, nothing more) are very different.

Using instance variables with Modern Runtime

I have several years of experience in Obj-c and Cocoa, but am just now getting back into it and the advances of Obj-C 2.0 etc.
I'm trying to get my head around the modern runtime and declaring properties, etc. One thing that confuses me a bit is the ability in the modern runtime to have the iVars created implicitly. And of course this implies that in your code you should always be using self.property to access the value.
However, in init* and dealloc(assuming you're not using GC) methods we should be using the iVar directly (in the current runtime).
So questions are:
Should we use property accessors in init* and dealloc with Modern Runtime?
If so, why is this different? Is it just because the compiler can't see the iVar?
If I need to override an accessor, can I still access that iVar that will be defined at runtime or do I have to define an actual iVar that the runtime will then use?
Again, if I can access the synthesized iVar, why can't I continue to do this for the init* and dealloc methods?
I read the docs several times, but they seemed a bit vague about all of this and I want to be sure that I understand it well in order to decide how I want to continue coding.
Hope that my questions are clear.
Quick summary of testing:
If you don't declare the ivar in legacy, compiler is completely unhappy
If you use #ifndef __OBJC2__ around ivar in legacy compiler is happy and you can use both ivar directly and as property
In modern runtime, you can leave the ivar undefined and access as property
In modern runtime, trying to access ivar directly without declaration gives error during compile
#private declaration of ivar, of course, allows direct access to ivar, in both legacy and modern
Doesn't really give a clean way to go forward right now does it?
In the current (OS X 10.5/GCC 4.0.1) compiler, you cannot directly access the runtime-synthesized ivars. Greg Parker, one of the OS X runtime engineers put it this way on the cocoa-dev list (March 12, 2009):
You can't in the current compiler. A
future compiler should fix that. Use
explicit #private ivars in the
meantime. An #private ivar should not
be considered part of the contract -
that's what #private means, enforced
by compiler warnings and linker
errors.
And why isn't there a way to
explicitly declare instance variables
in the .m file for the new runtime?
Three reasons: (1) there are some
non-trivial design details to work
out, (2) compiler-engineer-hours are
limited, and (3) #private ivars are
generally good enough.
So, for now you must use dot-notation to access properties, even in init and dealloc. This goes against the best practice of using ivars directly in these cases, but there's no way around it. I find that the ease of using runtime-synthesized ivars (and the performance benefits) outweigh this in most cases. Where you do need to access the ivar directly, you can use a #private ivar as Greg Parker suggests (there's nothing that prevents you from mixing explicitly declared and runtime-synthesized ivars).
Update With OS X 10.6, the 64-bit runtime does allow direct access to the synthesized ivars via self->ivar.
Since instance variables themselves can only be synthesized in the modern runtime (and must be declared in the #interface under 32-bit or pre-Leopard), it's safest / most portable to also declare the ivar
Should we use property accessors in init* and dealloc with Modern Runtime?
My rule of thumb is "possibly" for -init*, and "usually not" for -dealloc.
When initializing an object, you want to make sure to properly copy/retain values for ivars. Unless the property's setter has some side effect that makes it inappropriate for initialization, definitely reuse the abstraction the property provides.
When deallocating an object, you want to release any ivar objects, but not store new ones. An easy way to do this is to set the property to nil (myObject.myIvar = nil), which basically calls [myObject setMyIvar:nil]. Since messages to nil are ignored, there is no danger in this. However, it's overkill when [myIvar release]; is usually all you need. In general, don't use the property (or directly, the setter) in situations where deallocation should behave differently than setting the variable.
I can understand eJames' argument against using property accessors in init/dealloc at all, but the flipside is that if you change the property behavior (for example, change from retain to copy, or just assign without retaining) and don't use it in init, or vice versa, the behavior can get out of sync too. If initializing and modifying an ivar should act the same, use the property accessor for both.
If so, why is this different? Is it just because the compiler can't see the ivar?
The modern runtime deals with class size and layout more intelligently, which is why you can change the layout of ivars without having to recompile subclasses. It is also able to infer the name and type of the ivar you want from the name and type of the corresponding property. The Objective-C 2.0 Runtime Programming Guide has more info, but again, I don't know how deeply the details explained there.
If I need to override an accessor, can I still access that iVar that will be defined at runtime or do I have to define an actual iVar that the runtime will then use?
I haven't tested this, but I believe you're allowed to access the named ivar in code, since it actually does have to be created. I'm not sure whether the compiler will complain, but I would guess that since it will let you synthesize the ivar without complaining, it is also smart enough to know about the synthesized ivar and let you refer to it by name.
Again, if I can access the synthesized iVar, why can't I continue to do this for the init* and dealloc methods?
You should be able to access the property and/or ivar anytime after the instance has been allocated.
There is another SO question with similar information, but it isn't quite a duplicate.
The bottom line, from the Objective-C 2.0 documentation, and quoted from Mark Bessey's answer is as follows:
There are differences in the behavior that depend on the runtime (see also “Runtime Differences”):
For the legacy runtimes, instance variables must already be declared in the #interface block. If an instance variable of the same name and compatible type as the property exists, it is used—otherwise, you get a compiler error.
For the modern runtimes, instance variables are synthesized as needed. If an instance variable of the same name already exists, it is used.
My understanding is as follows:
You should not use property accessors in init* and dealloc methods, for the same reasons that you should not use them in the legacy runtime: It leaves you open to potential errors if you later override the property methods, and end up doing something that shouldn't be done in init* or dealloc.
You should be able to both synthesize the ivar and override the property methods as follows:
#interface SomeClass
{
}
#property (assign) int someProperty;
#end
#implementation SomeClass
#synthesize someProperty; // this will synthesize the ivar
- (int)someProperty { NSLog(#"getter"); return someProperty; }
- (void)setSomeProperty:(int)newValue
{
NSLog(#"setter");
someProperty = newValue;
}
#end
Which leads me to think that you would be able to access the synthesized ivar in your init* and dealloc methods as well. The only gotcha I could think of is that the #synthesize line may have to come before the definitions of your init* and dealloc methods in the source file.
In the end, since having the ivars declared in the interface still works, that is still your safest bet.
I am running into the same problem. The way I am working around not being able to access the synthesized instance variables is the following:
public header
#interface MyObject:NSObject {
}
#property (retain) id instanceVar;
#property (retain) id customizedVar;
#end
private header / implementation
#interface MyObject()
#property (retain) id storedCustomizedVar;
#end
#implementation MyObject
#synthesize instanceVar, storedCustomizedVar;
#dynamic customizedVar;
- customizedVar {
if(!self.storedCustomizedVar) {
id newCustomizedVar;
//... do something
self.storedCustomizedVar= newCustomizedVar;
}
return self.storedCustomizedVar;
}
- (void) setCustomizedVar:aVar {
self.storedCustomizedVar=aVar;
}
#end
It's not that elegant, but at least it keeps my public header file clean.
If you use KVO you need to define customizedVar as dependent key of storedCustomizedVar.
I'm relatively new to Obj-C (but not to programming) and have also been confused by this topic.
The aspect that worries me is that it seems to be relatively easy to inadvertently use the iVar instead of the property. For example writing:
myProp = someObject;
instead of
self.myProp = someObject;
Admittedly this is "user" error, but it's still seems quite easy to do accidentally in some code, and for a retained or atomic property it could presumably lead to problems.
Ideally I'd prefer to be able to get the runtime to apply some pattern to the property name when generating any iVar. E.g. always prefix them with "_".
In practice at the moment I'm doing this manually - explicitly declaring my ivars, and deliberately giving them different names from the properties. I use an old-style 'm' prefix, so if my property is "myProp", my iVar will be "mMyProp". Then I use #synthesize myProp = mMyProp to associate the two.
This is a bit clumsy I admit, and a bit of extra typing, but it seems worth it to me to be able to disambiguate a little bit more clearly in the code. Of course I can still get it wrong and type mMyProp = someObject, but I'm hoping that the 'm' prefix will alert me to my error.
It would feel much nicer if I could just declare the property and let the compiler/runtime do the rest, but when I have lots of code my gut instinct tells me that I'll make mistakes that way if I still have to follow manual rules for init/dealloc.
Of course there are also plenty of other things I can also do wrong...