Is strong identifier the default with #property statement? - objective-c

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.

Related

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

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;

Change with properties and ivars after ARC migration

I have used the "Convert to Objective C ARC" option in Xcode 4.3 to convert a project started in Xcode 4.0 to use ARC. After fixing errors that the tool found, I went trough the process where the migration tool has removed all the release messages as well as retain attributes in my properties declarations. So now I have all of my properties having only (nonatomic) attribute. From reading the documentation I still don't have a clear answer on what to do.
So my question is: In case you omit the keyword regarding the setter semantics (strong, weak, retain, assign) in the property declaration, what is the default attribute on properties when using ARC?
I found in the documentation that the default property attribute is assign. However, they also say that now the default attribute for ivars, in case you omit it, is strong.
To better explain my question, here is an example. I header file we have the declaration:
#property (nonatomic) MyClass *objectToUse;
and in our implementation we just have
#synthesize objectToUse;
If we then write inside some method:
self.objectToUse = [[MyClass alloc] init];
have we created an strong (retain) or weak (assign) reference? If we instead write
objectToUse = [[MyClass alloc] init];
by using the ivar have we changed the situation regarding the object retention policy? It seems to me that now with ARC, the best practice of using the properties for memory management is not the same practice anymore.
I've opened an Technical Support Incident. The engineer verified that the default was changed from "assign" to "strong". The reason is exactly the inconsistency you described. Now ivars and #properties have the same default.
He said both the documentation (and warnings some people are getting) are wrong and will be fixed. (The conversion tool is correct.) Until that is done, I would avoid the implicit default altogether. Always explicitly specify "strong", "weak", or "assign".
Edit: The clang documentation now officially documents this change.
The default relationship type is still assign, i.e. a weak ref. In addition, in ARC mode the compiler will generate an error when #synthesizeing accessors unless you explicitly specify a relationship type.
The difference between assigning to self.objectToUse and objectToUse is that the second form will always use ARC to retain or assign, while the first form will use copy if you specified a copy relationship.

Objective C : #property declaration and instance variable declaration

Though the question is basic, but I found it very crucial to understand to proceed with IOS programming. Sometimes we used to declare only instance variable and we don't set any associated property to it. Some where we just declare the properties and use synthesize to get or set the values. Sometimes I feel necessary to declare both in code, when compilation gives me warnings! What's the fundamental behind the manipulation of properties in Objective C. I know the basic requirement to create getter and setter for any instance variable, but when?
I have seen it many times we don't use property at all, and after that too we easily set and get variable's value. Also, different types of property like atomic, non atomic, strong, retain are very unclear to me. XCODE up-gradation to 4.2 has shaken my concepts about memory management. Can somebody please clear the cloud over my mind?
Properties are always the preferred way over direct ivar access, mostly of following reasons:
You can override a getter or setter in a subclass
You can define the "assigning behavior" (namely copy, assign, retain/strong, weak)
You can synchronize ivar access
Keywords:
copy: The object is copied to the ivar when set
assign: The object's pointer is assigned to the ivar when set
retain/strong: The object is retained on set
weak: In ARC this is like assign, but will be set to nil automatically when the instance is deallocated, also used in a garbage collected environment.
nonatomic: The accessor is not #synchronized (threadsafe), and therefore faster
atomic: The accessor is #synchronized (threadsafe), and therefore slower
Generally you should always synthesize an ivar. If you need faster access for performance reasons you can always access the synthesized ivar directly too.
While typing I saw that 'Erik Aigner' was faster with a good answer.
For een example on properties, synthesize and custom setter see my answer on stack:
Objective-C convention to prevent "local declaration hides instance variable" warning
For an stater tutorial on ARC see the explenation on Ray wenderlich his website:
Beginning ARC in iOS 5 part 1 and
Beginning ARC in iOS 5 part 2

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.

Whether C# interfaces and objective c #prototypes are same?

1) Whether C# interfaces and objective c #prototypes are same?
and when the function inside the prototype are optional and when they are compulsory.
2) What is meaning of #property (nonatomic, retain)
I am new to objective c environment ,struck in these concepts.Please help me to solve this.
Q: Whether C# interfaces and objective c #prototypes are same? and when the function inside the prototype are optional and when they are compulsory.
A: These are basically the same. Objective-C uses protocols like C# uses interfaces. By default all methods that you list are required (meaning the compiler will complain if it doesn't see the object implement the method, but the program will still compile).
Q: What is meaning of #property (nonatomic, retain)
A: #property means you are declaring a property. nonatomic means that the reading/writing of the property will not be thread safe, but it makes it much faster. If you need a thread safe property, you must use atomic (for which you simply leave out nonatomic, as atomic is the default. retain means that the retainCount automatically increases when you set the property, so you don't have to perform the [someVariable retain] call yourself. This has major memory management implications, so that's why you will frequently see a call to synthesize with an underscored ivar like so: #synthesize myObject = _myObject;
1) I assume you mean protocols. Protocols are close to interfaces in C# (and Java) but the semantics differ in that the method receiving the message does not need to implement the method. Then the message is ignored. Also sending messages (i.e. calling methods in C#) can be done on nil (i.e. null in C#) and nothing will happen.
2) #property(nonatmoic, retain) is the declaration of a property (which is a pair of methods, one getter and one setter). They can be automatically implemented using the #synthesize keyword. nonatomic is that no thread safety should be implemented. retain is that the objects reference count should be incremented/decremented in the setter.
1) I believe you are referring to protocols, formal protocols those woth the #protocol notation, are almost exactly the same as a C# interface, the diferrence ks that the protocol allows you to specify some optional methods, i.e. Some methods that you are not forced to implement.
2) A property is the equivalent of an instance variable for the class, and it can be #synthetized to automatically generate the setter and getters for this property. It can be declared atomic or non atomic, which means if the setter and getters will be performed as a singlw operation or not. It can also be declared as retain, copy or assign. Retain means that the ivar will send a retain msg to the obj in the generated setter, copy means that the setter will clone the instance and then send it a retain msg, while assign means that the value will just be assigned without a retain msg.
Hope that helps.
There is a huge difference that people are overlooking:
You can declare variables of type Interface in C# (as in Java) but you cannot declare variables of type protocol.