Friday, October 12, 2012

difference between a strong and weak pointer


Objective-C (programming language): In Objective-C, what's the difference between a strong and weak pointer?

 (1)
 

2 Answers

Strong and weak are keywords that help you manage the Automatic Reference Counting (ARC) of the XCode environment and are a part of the new way of managing memory in Objective-C. To understand the difference, you must first understand how memory is implicitly managed by objects in XCode. 

Each object has a property that tracks the number of other objects that require/reference it. This property is called the reference count. In the old way of doing things, you would specifically tell the object to be retained (increase its reference count). When you did this, you would also have to explicitly tell the object to decrease its reference count (release) when you were done with it.

When an object’s reference count reaches zero, it is destroyed and its memory return to the heap where it can be reused. If you forgot to retain the object, it could potentially be destroyed earlier than you intended and cause an error in your program—there are reasons why you wouldn’t retain an object, but I’ll get into that further down. If you forgot to release the object, or your program was structured in such a way it could never be released, it could reside in memory long after you were done with it, causing a memory leak which could slow your app down or potentially crash it.

Now, with ARC you no longer have to explicitly tell an object to be retained or released. Pointers are automatically created with strong references; they are automatically retained. In this case, the strong keyword is implied when creating pointers, though you can use it if you want.

However there are times when you don’t want to retain an object (i.e. increase its reference count). To do this, you use the weak keyword when creating the pointer. Your pointer will still point to the object, but if that object is destroyed then using the pointer will cause a program error.

Why would you use a weak reference?

Well, one reason is if you have objects in parent-child relationships where the parent keeps pointers to its children and every child keeps a pointer to its parent. The potential with this structure is that you could no longer need your parent object and XCode will implicitly release it, but because its children keep a reference to it, the parent and its children can remain in memory even though you no longer have a way of accessing them. This is called a retain cycle.

To avoid the retain cycle, the children objects should only maintain a weak pointer to their parents. The reason for this is that when the parent is told to destroy itself, the children would be destroyed first so there is no chance they could access their parent after it had been destroyed.

No comments: