62

What is the difference b/w NSArray and NSMutableArray?

exebook
  • 32,014
  • 33
  • 141
  • 226
g.revolution
  • 11,962
  • 23
  • 81
  • 107

3 Answers3

117

NSMutableArray (and all other classes with Mutable in the name) can be modified. So, if you create a plain NSArray, you cannot change its contents later (without recreating it). But if you create an NSMutableArray, you can change it — you'll notice it has methods like -addObject: and -insertObject:atIndex:.

See the documentation for details.

jtbandes
  • 115,675
  • 35
  • 233
  • 266
5

The "mutable" types are classes which can be changed after they've been initialized, like NSMutableString vs NSString.

Shaggy Frog
  • 27,575
  • 16
  • 91
  • 128
  • 1
    `NSMutableString` is derived from `NSString`. Consequently, you can't rely on a "`NSString*`" you receive from outside to be immutable. You can only assume `NSMutableString*` is mutable. `NSString*` can be mutable or immutable. That's why you might want to call `[str copy]` when the instance is assigned to some property in your class. – Mehrdad Afshari Aug 28 '09 at 05:55
  • You can't change an NSString once it's built. See http://stackoverflow.com/questions/905396/the-final-word-on-nsstrings-mutable-and-immutable. As for why you use copy, see http://stackoverflow.com/questions/387959/nsstring-property-copy-or-retain – Shaggy Frog Aug 28 '09 at 06:11
  • 1
    Shaggy: You can't change an *instance* of `NSString` class. This is not the issue. The issue is that a "`NSString*`" does not necessarily point to an instance of `NSString` class. It can also point to instances of classes derived from `NSString`, like `NSMutableString`. Therefore, you can't rely on an `NSString*` you have received from the outside world to be immutable. – Mehrdad Afshari Aug 28 '09 at 06:57
  • Okay, I understand now. I'll delete that portion of my answer. – Shaggy Frog Aug 28 '09 at 07:07
1

NSArray : in NSArray we can not change index.... Means fix array.

NSMutableArray : in NSMutableArray we can change index and also add the value in array at run-time..

Vvk
  • 4,031
  • 29
  • 51
Jagat Dave
  • 1,643
  • 3
  • 23
  • 30