What is the correct way to declare a readonly property for ios using ARC - objective-c

I am new to iOS development in general and have never dealt with manual reference counting (retain, release, autorelease). As such I don't have a good understanding of what magic ARC is performing.
I thought I understood until I was asked what type of ownership (weak, strong, assign, etc) should be given to a readonly property pointing at an object, such as:
#property (readonly,nonatomic) NSString* name;
I read here
Questions about a readonly #property in ARC that leaving off the strong/weak won't actually compile unless you specify a backing variable when you #synthesize the property; I just so happened to be specifying a backing ivar like this:
#synthesize name = _name;
Now I understand that the default 'lifetime qualifier' of a variable is strong, from here: http://developer.apple.com/library/ios/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011226-CH1-SW4
So to cut a long story short - I am indirectly defining my property as (readonly,nonatomic,strong) as the _name ivar is implicitly declared as __strong.
I have a few questions:
Is strong the correct lifetime qualifier to use? I assume that it is, otherwise the object backing my NSString* wouldn't be owned anywhere and would thus be freed automatically (coming from Java land this makes sense as all references are strong by default).
Are there any other modifiers which make sense in this situation, such as copy or assign?
Does declaring the property as (readonly,nonatomic,strong) and (readonly,nonatomic) make any difference to the code which consumes the property? eg. does declaring it without the strong keyword cause the object pointer to be stored as __unsafe_unretained where the strong property would be stored in a __strong pointer?
Thanks!
EDIT
So as I understand now, the following applies to readonly properties:
For non-NSObject* types (int, float, void*, etc) use (readonly, assign).
For object pointers, use (readonly, strong) or (readonly, copy) - these function the same for readonly properties but you may want the copy semantics if you extend/subclass and redeclare the property as readwrite.
For object pointers, (readonly, weak) only makes sense if you are going to be storing an already weak pointer in that property (that pointer must be strong elsewhere or the object will be deallocated).

strong is correct to use if you want to keep a strong (owning) reference to whatever it is that you are pointing to. Usually, you do want strong, but in order to prevent circular references (particularly in parent/child relationships where if the parent points to the child and the child points to the parent, they will never be released) you sometimes need to use weak references. Also, if you want to keep a pointer to an object that you don't own but want it to be valid only as long as it exists, then you want to use a weak pointer because when it gets deallocated by the owner, your pointer will automatically get set to nil and won't be pointing to memory that it shouldn't be.
assign is used with scalar values, and is the default setter. copy makes sense if you want to automatically make a copy of the object and set your pointer to the copy instead of pointing to the original object. It only makes sense to do this if you have a specific need (usually because you don't want the object to mutate on you).
The link that you provided which shows that __strong is the default (and therefore you don't need to specify it) refers to variables and not to declared properties. The default for declared properties is assign so it certainly will make a difference. If you were wanting assign however, it makes no difference whether you specify it or not (other than just to be clear that it is what you wanted).
EDIT: However, as Jacques pointed out, this is changing with LLVM 3.1 and the default is changing from assign to strong. In this case, it makes absolutely no difference whether or not you specify strong and can leave it out if you want. Personally I think that it is good to spell it out (especially since there is a conflict between different versions) so that everyone looking at the code is on the same page. Others may disagree on this point though. :)
I would suggest reading the Declared Properties section of The Objective-C Programming Language here: <document removed by Apple with no direct replacement>.

One additional point: properties can get redeclared from readonly to readwrite. For example, a subclass may make a read-only property from the superclass read-write, similar to how many Cocoa classes have subclasses that add mutability. Likewise, a property may be publicly read-only but the class may redeclare it read-write for internal use in a class extension. So, when the class sets its own property it can take advantage of a synthesized setter that does memory management properly and emits appropriate Key-Value Observing change notifications.
As things currently stand, all of the other attributes of the property have to be consistent. It's conceivable that the compiler could relax this requirement. (Some consider it a bug.) Anyway, that's one reason to declare a readonly property with an ownership attribute like strong, copy, or weak – so that it will match the readwrite redeclaration elsewhere.
With regard to your question 3, are you asking if the ownership qualifier affects code which calls the getter? No, it doesn't.

These 2 lines of code work for me:
.h file:
#property (nonatomic, readonly, copy) NSString *username;
.m file:
#property (nonatomic, readwrite, copy) NSString *username;

Related

Objective-C property attributes best practices

After multiple searches and reads about property attributes, I still can't understand them completely and create a reflex of using them correctly.
I have multiple questions:
1) What does a default attribute mean?
As I understood, not specifying an attribute in a "group", the default one is used, so this:
#property NSString *string;
is atomic, right?
By this logic, this article says that strong and assign are defaults, so if I have:
#property (nonatomic) NSString *string;
is the string property strong or assign?
How are the available attributes "grouped"? Or as Xcode words this, what attributes are mutually exclusive?
2) Are there any generic rules that one should follow?
For example, I saw one comment that said that you should use copy for classes with mutable variants like NSString, NSArray.
And another one that said that you should use assign for C objects.
So, is it a good idea to always use:
#property (copy, nonatomic) NSString *string;
#property (assign, nonatomic) CGFloat float;
?
What other standard practices exist for property attributes?
3) What problems could arise if I use "wrong" attributes? What if I just use nonatomic for all the properties in a project?
1a) The default attributes for a property are atomic, and strong (for an object pointer) or assign (for a primitive type), and readwrite. This assumes an all ARC project.
So #property NSString *string; is the same as #property (atomic, strong, readwrite) NSString *string;. #property int value; is the same as #property (atomic, assign, readwrite) int value;.
1b) Attributes are grouped as follows:
atomic/nonatomic
strong/weak/assign/copy
readwrite/readonly
Pick one and only one from each of those three groups.
Actually, the latest Objective-C adds support for nullable/nonnull with the default being nullable.
2) General rules are as you say.
Object pointers should usually be strong.
Primitive types should be assign.
weak should be used in child/parent references to avoid reference cycles. Typically the parent has a strong reference to its children and the children have a weak reference to their parent. Delegates are typically weak for the same reason.
copy is typically used for NSString, NSArray, NSDictionary, etc. to avoid issues when they are assigned the mutable variant. This avoids the problem of the value being changed unexpectedly.
There's a big "gotcha" using copy with NSMutableString, NSMutableArray, etc. because when you assign the mutable value to the property, the copy attribute results in the copy method being called which gives back a non-mutable copy of the original value. The solution is to override the setter method to call mutableCopy.
3) Using the wrong attribute could have serious problems depending on the needs of the property and the attribute being used.
Using assign instead of strong for an object pointer is probably the worst mistake. It can lead to app crashes due to trying to access deallocated objects.
Using nonatomic instead of atomic on a property that will be accessed concurrently on multiple threads may lead to really hard to find bugs and/or crashes.
Using strong instead of copy for NSString or NSArray (and other collections) can possibly lead to subtle and hard to find bugs if mutable variants were assigned to the property and other code later modifies those values.
#rmaddy's answer is a good one.
I would add the following.
If you are creating (or have inherited) classes that interoperate with Swift, it is very useful to include nullable or nonnull property attributes. If you add it in any part of a header file, you will need to specify it for all parts of the header file (compiler warnings will help you). It's even quite useful for Objective-C callers to know from the method signature what may and may not be a nil value.
Another property of note is class. You can add a property to the class.
Adding these two items together, and if you are implementing a singleton,
+ (MyClass *)sharedInstance;
it's quite useful to define it as a property:
#property (class, nonatomic, nonnull, readonly) MyClass *sharedInstance;
(In which case you are required to add a backing variable for it as described in this article)
This will let you access the shared instance via dot notation.
[MyClass.sharedInstance showMeTheMoney:YES];
And in Swift, the rather annoying
MyClass.sharedInstance()?.showMeTheMoney(true)
turns into
MyClass.sharedInstance.showMeTheMoney(true)
‡ maybe it's just 3 characters to you, but it keeps my head from exploding mid-day.
Edit:
I would add, try out
+ (instancetype)shared;
This 1) shortens the naming to concur with modern Swift convention, and 2) removes the hardcoded type value of a (MyClass *).

Is strong identifier the default with #property statement?

I'm learning Objective-C and the Cocoa Framework (via Aaron Hillgass' book) and trying to figure out why the following line includes the "strong" identifier.
#property (strong) NSManagedObjectContext *managedObjectContext;
As I understand it, strong is the default so why do I need to explicitly declare it?
You can declare it without writing anything, But what happens when you come back to code or some other developer looks at your code?
You might have the knowledge that the default will be set to strong, but junior level programmer will get so confused to determine whether the declared variable is strong or weak.
Agree with Richard.
//Strong and Weak References
ARC introduces two new object reference qualifiers: strong and weak.
Under ARC, all object reference variables are strong by default.
And this doesn’t apply to just properties;
the default identifier with #property statement is assign for non-object types,
for object type should be strong.
all object references - property values, instance variables, automatic variables,
parameter variables, and static variables - act like a retain property under ARC.
In The Objective-C Programming Language:
assign
Specifies that the setter uses simple assignment. This
attribute is the default.
That is, the default attribute for the setter semantics is assign, rather than strong.

In Objective-C with ARC, is it true that we usually only need to specify nonatomic as property attributes?

It is strange that in Big Nerd Ranch iOS 5 book (p.73) and Programming iOS 5 book (O'Reilly, p.314) (updadte: even Kochan's Objective-C book Fourth edition), in the context of ARC, they say the default for properties attribute is assign... But Apple's documentation says the default is strong.
I also tried a simple program where if I don't specify strong, the program works ok, and if I specify strong, it works the same, and when assign is used instead, the compiler shows a warning, so it seems the default is indeed strong.
So if most of the time, we want
#property (nonatomic, readwrite, strong) NSMutableArray *foo;
then we can just write
#property (nonatomic) NSMutableArray *foo;
as the other two (readwrite and strong) are the default?
readwrite and strong, are indeed the default under ARC*. Under manual reference counting, assign was (is) the default. I prefer to explicitly specify these, because it makes it clearer what the #property's parameters are instead of relying on the person reading the code knowing what the defaults are.
*strong is the default assuming you've either let the compiler synthesize an instance variable for you, or have declared an instance variable without an explicit ownership qualifier (in which case the ivar is __strong by default anyway). Otherwise, the default property ownership type matches the ownership qualifier in the ivar's declaration. So, if you explicitly declare an ivar with __weak, then declare an #property for it without an ownership qualifier, the synthesized property will be weak. This is all documented in the Clang ARC documentation.
By default, an object property is strong, atomic, readwrite. See
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html

Questions about a readonly #property in ARC

In my interface (.h) file, I have
#property(readonly) NSString *foo;
and in my implementation (.m) file, I have
#synthesize foo;
With ARC turned on, the compiler gives me this error: Automatic Reference Counting Issue: ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute.
The error goes away if I add a strong, weak, or copy to the property. Why is this? Why would there be any differences between these things for a read-only property, what are those differences, and why does the programmer have to worry about them? Why can’t the compiler intelligently deduce a default setting for a read-only property?
Another question while I’m at it: strong, weak, or copy are the only things that make sense in ARC, right? I shouldn’t be using retain and assign anymore, should I?
You've declared a #property that doesn't have a backing ivar. Thus, when the compiler sees #synthesize, it tries to synthesize a backing ivar for you. But you haven't specified what kind of ivar you want. Should it be __strong? __weak? __unsafe_unretained? Originally, the default storage attribute for properties was assign, which is the same as __unsafe_unretained. Under ARC, though, that's almost always the wrong choice. So rather than synthesizing an unsafe ivar, they require you to specify what kind of ivar you want.
With the latest version of Xcode and recent clang compilers, this error no longer occurs. You can specify a property as #property(nonatomic, readonly) NSObject *myProperty; in the interface, synthesize it in the implementation, and the resulting ivar is assumed to be strong. If you want to be explicit or choose weak, you can do so in the original property, like #property(nonatomic, readonly, retain). Objective-C is incrementally becoming less redundant.
It is here as a declaration to the rest of your code.
When you a access the property of this class from an other part of your code, you need to know if the object you get is strong or weak.
It used to be more obvious when ARC didn't exists, because the programmer needed this information. Now, ARC makes a lot of things transparent, so it is true, you might wonder why it is still here.
Why can’t the compiler intelligently deduce a default setting for a read-only property?
I assume it would be pretty easy to set the convention that no keyword means strong or means weak. If it hasn't been done, they surely had a reason.

Simple Properties in Objective-C Classes

I've bene working with Objective-C for a while now, and so far I have never really needed to craft my own classes, properly.
I am a bit confused with the two arguments you can give the #property(a, b) declaration in a header file. When creating outlets to Interface Builder I usually do #property(nonatomic, retain) but I have no idea what this means.
I'm writing a simple class which has a set of properties which will be set from the outside, like [instance setName:#"Bla Bla Bla"]; or I guess like instance.name = #"Bla#" but I would rather the first option.
How would I declare this kind of property on a class?
Thanks in advanced!
Sorry for the n00bish question :-)
The #property parameter gives you a hint on the property behavior:
nonatomic tells you that setting/getting the property value is not atomic (wrt to multiple thread access)
retain tells you the object will be retained by the property (i.e. The receiver will take ownership of the object). The othe options are "copy" (the object is copied using -copy. This is generally the good choice for value objects like NSStrings) and "assign" (the object is just assigned to the property without retaining it. This is generally the good choice for delegates or datasources). These 3 options are only useful for ObjC objects, not simple C type properties.
See http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html for more info.
For your case, you'll likely use:
#property(copy) NSString* name;
Or:
#property(nonatomic, copy) NSString* name;
If you don't need the property setter/getter to be atomic.