BNRItemStore getter Method for allItems


#1

Last summer I completed most of the 2nd edition last year, and went on to develop my first app (all be it a simple one) which is in the iTunes store.

I then returned to my studies at University, and did not manage to continue my learning as much as I would have liked, however did manage to develop a second app before the end of the year.

Anyway, I decided to purchase the Objective-C Programming, The Big Nerd Ranch Guide, and the third edition of iOS Programming to get up to speed with ARC, iOS 5…

What am I finding, is that now and again I am questioning parts of the code we type in from the book (which I did not do first time round), which hopefully is by no means a bad thing? I put it down to simply being slightly overwhelmed first time round by what I was doing, along with not fully understanding every single piece of code.

Now to my questions:

In this chapter, when creating the BNRItemStore, we create a getter method for allItems, which returns a pointer to a NSArray. My first question is why do we return a pointer to a NSArray, and not a NSMutableArray which is what we declared the variable as?

Secondly, why have we created the getter method for allItems, instead of declaring a read only property for it?

Thanks,
Nick

http://myfirstiphoneapp.co.uk


#2

So the getter method says it returns an NSArray (while in reality it actually returns an NSMutableArray, because allItems is an NSMUtableArray) to tell the user of the BNRItemStore that they shouldn’t modify the array returned by this method. Only the store should be allowed to insert, reorder or delete objects in this array because in the future, changing the contents of the array will have more ramifications (like saving things to the disk).

Making the getter return a non-mutable type doesn’t strictly enforce this, if you wished to strictly enforce this, you would implement the getter to return an immutable copy of the mutable array.

Making a read-only property would mean that the type of the return value would be NSMutableArray and someone might directly modify that array without going through the store


#3

Hi Joe,

Many thanks for the response.

I kind of thought that the pointer returned would have to be a NSArray, however did not know the real reason behind.

And now that you have given the reason, I now understand the reasoning behind the getter method as you have explained.

Thanks,
Nick


#4

Oops, and I guess I should have looked in the second edition section first :blush: