Question

I am starting with Objective-C development and trying to understand the weak and strong references. I think I understand it, but I am not sure about it...

Let consider that code:

@interface SomeClass {} 
@property (nonatomic, weak) NSString* propertyName;
@end

Now, if I invoke somewhere in the code something like this:

NSString* s = someClassInstance.propertyName;

The reference counter is not incremented. Is my understanding correct?

  • Doubt 1: What is the reference counter value for propertyName?

  • Doubt 2: So... Could you give an example of when I can get the strong reference to this property? I hope you know what I mean or what I do not understand...

I will get the weak reference.

Was it helpful?

Solution

Declaring propertyName as a "weak" property means two things:

  1. When you assign an object to propertyName, that object's reference count is not incremented.

  2. When the object that propertyName points to is deallocated, propertyName will be set to nil.

Assigning the value of propertyName to another variable may or may not have any impact on the reference count. If you assign it to a strong property, you will almost certainly increase the refcount (since that is part of the semantics of a strong property). But ultimately the compiler will decide if modifying the reference count is necessary.

It's important to understand the concept of object ownership in Objective-C, whether you are using ARC or not, but the details of the actual reference count for a given object at any given moment are not so useful. Remember this: a strong property owns an object. A weak property does not.

OTHER TIPS

First of all "strong" is synonym of "retain" and "weak" is synonym for "assign" in ARC enabled application.

answer to Doubt 1: Its retain count will be equal to the retain count of the object it is storing. as it is just a reference.

answer to Doubt 2

Answer to your doubts:

You should refer this link for understanding strong and weak type property

http://www.raywenderlich.com/5677/beginning-arc-in-ios-5-part-1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top