Book Image

Objective C Memory Management Essentials

Book Image

Objective C Memory Management Essentials

Overview of this book

Table of Contents (18 chapters)
Objective-C Memory Management Essentials
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Object immutability


Most of the classes provided by Cocoa and Cocoa Touch create objects with immutable values. In short, an immutable object has its contents set only once, and can never modify its values after that. These objects have their contents specified during their creation. The object's creation might occur in the initialization process or later, but it happens once.

Here, we can see an array that is initialized and created at the same time. Its contents are immutable:

/*
  =============================================
  sampleArray is allocated, initialized and created with the strings "Item 1" and "Item 2"
  =============================================
*/
NSArray *sampleArray = [[NSArray alloc] initWithArray:@[
              @"Item 1",
              @"Item 2"]];
//This will throw a compile time error as NSArray is not mutable.
[sampleArray addObject:@"Item 3"];

In the preceding line of code, [sampleArray addObject:@"Item 3"]; will show you a compile time error as sampleArray is...