iOS Development

Course No. 10-152-139

Chapter 15 — Objects and Memory

On pointers and their values

  • Objects can only be accessed via a pointer.
    • now is a pointer that can hold an address of a location in memory where and instance of NSDate lives.
  • Pointer to nil.
    • NSDate pointer initialized to nil.
    • The local variable currentTime is part of the stack frame for main() and points to nil. There are no objects on the heap yet.


  • Pointer initialized to NSDate.
    • currentTime points to an initialized NSDate object.
    • A NSDate object now exists on the heap and is pointed to by the local variable currentTime.


  • Pointer to different NSDate.
    • currentTime is a variable, so it can be changed to point to a different NSDate object.
    • currentTime now points to a new NSDate object on the heap and the first NSDate object is now orphaned.


  • Holding on to both NSDate objects.
    • Changing @currentTime@’s value and still accessing the first NSDate object.
    • currentTime now points to a new NSDate object on the heap and startTime points to the first NSDate object on the heap.


Memory management

  • The Stack is an orderly stack of frames. Each frame is deallocated when the functin using it ends.
  • The Heap is a heaping pile of memory available to your program and is where your objects live.
    • Heap management is important. Running low on memory will cause your Mac app to perform badly.
    • Running low on memory will cause your iOS app to crash.
    • In the case of orphaning the original NSDate, nothing is pointing to it, so it needs to be destroyed.


ARC

  • ARC is the setting that instructs the compiler to destroy unreferenced objects. ARC stands for Automatic Reference Counting. Each Object maintains a count of how many references to itself there are.
    • When currentTime is changed to point to a new NSDate object, the original NSDate object loses a reference, and ARC decrements its reference count. The new NSDate object’s reference count is incremented.
    • Since currentTime no longer points to the original NSDate object, and there are no references to it, it will be destroyed so that its memory can be reclaimed.


  • Holding on to both NSDate objects.
    • Creating startTime and pointing it to the same value as currentTime increments the reference count to the original NSDate object.


    • Then create a new NSDate object for currentTime to point to. The original NSDate object’s reference count is decremented, and a new NSDate object is created with a reference count of 1.


  • What if you are finished with an object?
    • When you are done with an object, just set any references to it to nil.