Immutable objects

Most beginning programmers are surprised by the immutability of NSArray, NSSet, and NSDictionary. Why would anyone want a list that cannot be changed? The reasons are performance and security:

You do not trust the people you work with. That is, you want to let them look at an array, but you do not want them to be able change it. A gentler approach is to give them an NSMutableArray but tell them it is an NSArray. For example, consider the following method:

/​/​ ​R​e​t​u​r​n​s​ ​a​n​ ​a​r​r​a​y​ ​o​f​ ​3​0​ ​o​d​d​ ​n​u​m​b​e​r​s​ -​ ​(​N​S​A​r​r​a​y​ ​*​)​o​d​d​s​ {​ ​ ​ ​ ​N​S​M​u​t​a​b​l​e​A​r​r​a​y​ ​*​o​d​d​s​A​r​r​a​y​ ​=​ ​[​[​N​S​M​u​t​a​b​l​e​A​r​r​a​y​ ​a​l​l​o​c​]​ ​i​n​i​t​]​;​ ​ ​ ​ ​i​n​t​ ​i​ ​=​ ​1​;​ ...

Get Objective-C Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.