Difference in strong and weak pointers in ObjectiveC

Before writting this, I assume you know basic knowledge of ObjectiveC and its well known topic of discussion Memory Management If you do not know you can follow tutorials on ObectiveC &  ObjectiveC Memory Management, Here I am going to explain how strong and weak pointers are different in ObjectiveC with some code example.

Consider Sample classes TechClass & MyClass explain, one class have 2 ivars which which points to object of MyClass with strong and weak reference viz. strogPntr & weakPntr as shown below


1
2
3
4
5
6
7
8
@interface MyClass()
@end

@interface TechClass(){
    
    MyClass * strogPntr;
    __weak MyClass * weakPntr;;
}

Now we create MyClass object and assign it to strogPntr. same object is pointed by weakPntr. Now if we assign nil to weakPntr it will not deallocate that object because still there is strong pointer referring to that pointer.


1
2
3
 strogPntr = [MyClass new];
 weakPntr = strogPntr;
 weakPntr = nil;

Pictorial representation of above code is given below
weak-pointer-nil

Lets see whats happens when we try other way around i.e, assigning nil strogPntr. what do you expect here? will object get deallocated or keeps on hanging with weakPntr  pointer ???
Correct answer is object will be deallocated because object do not have any strong pointer pointer to created object of MyClass also due to this now weakPntr will automatically point to nil.


1
2
3
 strogPntr = [MyClass new];
 weakPntr = strogPntr;
 strogPntr = nil;
Pictorial representation of above code is given below


Now onwards keep in mind  that if you want to persistent object inside any viewcontoller/custom object never ever nil all out strong pointer to object else the object will be revoked by system even you have tones of weak pointers to the object


keepRocking