user1099123
user1099123

Reputation: 6683

Do weak references in objective c get randomly deallocated?

In the example below, I've defined abc to be a weak reference.

@interface myClass : NSObject
    @property (nonatomic, weak) Line *abc

@end

- (id)init
{
    abc = [[Line alloc] init]
}

Can abc get deallocated randomly since no one strongly points to it? I'm struggling to understand how things get deallocated in languages like objective c. Since there is no garbage collector, what exactly removes it from memory(by simply setting it to nil and called dealloc?)?

The way I imagine it working is when myClass gets set to nil, it will call dealloc on all of the instance variables that have a reference count of 0. Until myClass gets set to nil, abc will always be in memory. Am I correct?

Upvotes: 0

Views: 519

Answers (1)

Shamsudheen TK
Shamsudheen TK

Reputation: 31311

A weak reference is a reference to an object that does not stop it from being deallocated.

In other words, it does not create an owner relationship. Whereas previously you would do this:

In ARC you use weak to ensure you do not own the object it points to.

Read more information here

Upvotes: 1

Related Questions