Reference Counting in Swift

Understanding various property attributes such as weak, retain is an important aspect of reference counting in Swift and memory management for iOS.

ARC and Reference Counting in Swift

ARC is XCode way’s of memory management. It basically means when would the memory free up of an object.

All variables are strong by default. We use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialization. Here is also a little comparison of all variable property attributes:

  • weak –  it says “keep this as long as someone else points to it strongly
  • atomic – multi threaded. Locks the value before any changes. so it turns something, even though it may not be correct
  • nonatomic – a single thread. Doesn’t lock the value, it clears it in the process of adding a new one. As a result, you might get nil
  • Retain is a pointer to an object. The setter will add a retain count to the object
  • Assign: When calling the getter of an assign  property, it returns a reference to the actual data.
Reference Counting in iOS

Summary

Reference counting is the process keeping an eye on the objects instantiated from any class and making sure they are released when no longer needed.

Interested in learning more in-depth concepts?

If you are interested in learning more about mobile app development, I invite you to join my complete iPhone or Android course(s):

Leave a Comment