Manoj Karki Manoj Karki - 1 year ago 61
iOS Question

weak property objective c memory management

I have a view controller with a weak NSString property

@property (nonatomic, weak) NSString *weakString;

In viewDidLoad I initialize as follows

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_weakString = @"i am weak";

In my understanding the weak property may get deallocated anytime is it safe to declare property with weak attribute like this?
And when I do this,

_weakString = [NSString alloc]init];

Compiler warns me that assigning retained object to weak variable, object will be released after assignment. Why compiler giving this warning? and why compiler doesnt give warning when assigning string literal to my weak NSString property. Any help would be appreciated.Thanks.

Answer Source

Retain property: strong -it is retained, old value is released and it is assigned -retain specifies the new value should be sent -retain on assignment and the old value sent -release -retain is the same as strong. -apple says if you write retain it will auto converted/work like strong only. -methods like "alloc" include an implicit "retain"

When use Weak property: The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).

You can not retain the weak property like this, _weakString = [NSString alloc]init]; you have to use strong property.

If you wanted to dealloc the memory, you can nil your variable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download