Strong vs Weak

Day 4

One thing I’ve never had to worry about before with Web languages is memory management and reference counting. Thankfully iOS 5 has made the transition a little easier for me with Automatic Referencing Counting, which takes over a lot of the heavy lifting. Even so, there are still considerations that need to be made whenever a property is declared.

You have a choice between (strong) and (weak) when defining a property. In this post I’ll explain the difference between the two.

Strong

This is the default state of a pointer, though I still like to explicitly state strong for clarity. A strong pointer will be retained as long as the class in which it was allocated remains.

Weak

A weak reference means the pointer has no owner, therefore it will be deallocated as soon as it is no longer needed (that is, nothing else is pointing to it).

Most commonly, you would use weak for IBOutlets, such as UITextFIeld, UILabels and UIButton objects. Here’s an example:

In this case, I’m creating an IBOutlet for a button (theButton) in my view within my controller. The theButton object belongs to my view, not my controller, so in this case a weak attribute makes more sense than strong. In fact, as a general rule IBOutlets should always be set to weak.

  • Pingback: Atomic vs Nonatomic | Click, Flick, Boom!

  • Gabriel
    i am new to objective c, so I would like to see more examples, thanks!
  • Ronit
    Again a Gud One...
    • TomLongo
      Thanks mate. I've really left this blog alone lately, you're inspiring me to get back into it!