I'm watching an old WWDC video and in their splitViewController example, they do this in the delegate methods for the splitViewController:
NSMutableArray *toolBarItems = [[toolbar items] mutableCopy];
[toolbarItems removeObjectAtIndex:0];
[toolbar setItems: toolbarItems animated YES];
[toolbarItem开发者_如何转开发s release];
Is there a general good practice in making a mutableCopy like this for your data in certain methods? I haven't seen this before and as a new programmer, do not know when or why I would/should use a copy of something instead of the original. I guess I can see it in something like a list where it is already ordered a certain way, and maybe I would make a copy of it to reorder it in a different way. But I do not know if that's their reasoning here, and if there are OTHER best practices to do this. Thanks!
Mutable means change-able. So, if you need to change the array, you need to obtain a mutable version of it. NSArray
implies NS(Immutable)Array
meaning you can't change it's data.
In the example you've provided, the array provided by [toolbar items] is immutable. If you want to change it, you have to make a mutable version of it, modify that instead, and then pass the modified copy back to toolbar, via its setItems:animated: method. The modification in this case is removing the first toolbar item in the array, but to reiterate, you can't modify an immutable array.
精彩评论