Manoj Karki
Manoj Karki

Reputation: 270

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.

Upvotes: 2

Views: 980

Answers (2)

dahiya_boy
dahiya_boy

Reputation: 9503

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.

Upvotes: 1

Ajjjjjjjj
Ajjjjjjjj

Reputation: 675

If you want to allocate memory to a object, then you cannot use weak reference of any object.

You either have ARC on or off for a particular file. If its on you cannot use retain release autorelease etc... Instead you use strong weak for properties or __strong __weak for variables (defaults to __strong). Strong is the equivalent to retain, however ARC will manage the release for you.

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).

The 'toll free bridging' part (casting from NS to CF) is a little tricky. You still have to manually manage CFRelease() and CFRetain() for CF objects. When you convert them back to NS objects you have to tell the compiler about the retain count so it knows what you have done.

Upvotes: 0

Related Questions