Home > Articles > Programming > Mac and iOS Programming

  • Print
  • + Share This
This chapter is from the book

Pointer Variables and Object Ownership

Pointer variables convey ownership of the objects that they point to.

  • When a method (or function) has a local variable that points to an object, that method is said to own the object being pointed to.

  • When an object has an instance variable that points to another object, the object with the pointer is said to own the object being pointed to.

Think back to your RandomPossessions application as a whole. Or, better yet, reopen RandomPossessions.xcodeproj and have another look at the code in main.m. In this application, an instance of NSMutableArray is created in the main function, and then 10 BNRItem instances are added to the array.

Figure 3.3 shows the objects in RandomPossessions and the pointers that reference them.

Figure 3.3

Figure 3.3 Objects and pointers in RandomPossessions

The NSMutableArray is pointed to by the local variable items within the main function, so the main function owns the NSMutableArray. Each BNRItem instance owns the objects pointed to by its instance variables.

In addition, the NSMutableArray owns the BNRItems. Recall that a collection object, like an NSMutableArray, holds pointers to objects instead of actually containing them. These pointers convey ownership: an array owns the objects it points to.

The relationship between pointers and object ownership is important for understanding memory management in iOS.

  • + Share This
  • 🔖 Save To Your Account