When to use "assign"?


#1

I’m trying to understand why I would ever want to use assign in a property declaration. It seems to me that I’d never want to use it! So I must be misunderstanding something…

Let’s say I have declared 3 properties like this:

@property (nonatomic, retain) NSString *firstStr;
@property (nonatomic, copy) NSString *secondStr;
@property (nonatomic, assign) NSString *thirdStr;

And in the implementation section of my class I have 3 statements like this:

[self setFirstStr:someString];
[self setSecondStr:someString];
[self setThirdStr:someString];

The 1st statement will cause the firstStr instance var to point to someString. If firstStr isn’t already on the pile, it will be added to the pile. The heap will be unaffected. The object someString will increase its own retain count by 1. It has gained a new (additional) parent, firstStr.

The 2nd statement will cause the secondStr instance var to point to a new object. This new object will be added to the heap. It will be a copy of someString. The new object will have its retain count set to 1, and secondStr will be its parent. We no longer care what happens to the object someString as secondStr has no relationship to it.

The 3rd statement will cause the thirdStr instance var to point to someString. If thirdStr isn’t already on the pile, it will be added to the pile. The heap will be unaffected. This operation will have no effect on the object someString. Also thirdStr has not become a parent. Therefore if someString is released and deallocated by another thread/method/statement… then the instance var thirdStr will become a casualty of premature deallocation.

Assuming I have understood correctly, why would anyone ever use assign? It seems like an accident waiting to happen, no?


#2

Hi,

Retain is more common but there are cases where you have to use assign:

  1. When declaring properties for primitive types (NSInteger, BOOL etc).

  2. When you need to stop a cyclic relationship being created i.e. A retains B and B retains A
    There is a “For the more curious” section in Chapter 6 that explains this (and the consequences).

This is a good post that may help http://cocoawithlove.com/2010/06/assign-retain-copy-pitfalls-in-obj-c.html it also highlights some differences when using copy for mutable and non-mutable classes.

Gareth


#3

Thanks Gareth! Good link, also.