SoFunction
Updated on 2025-04-12

IOS development The difference between NSMutableArray and NSArray

IOS development The difference between NSMutableArray and NSArray

First, let’s take a look at the difference between the two:

NSArray and its subclass NSMutableArray manage collections of objects called arrays.
 NSArray creates static arrays, and NSMutableArray creates dynamic arrays.

NSMutableArray is a subclass of NSArray. NSArray creates static arrays, while NSMutableArray is a dynamic array. In other words, NSArray cannot be modified after it is established, while NSMutableArray can be modified.

Since in ObjC, if you simply look at the function addObject, you will find that the elements of the array are of id type, that is, pointers.

-
 (void)addObject:(id)anObject

In this way, non-pointer-type data such as NSUInteger and BOOL cannot be inserted into the array, it will be fatal...

What should I do if I press these contents? Yes, type conversion, ObjC provides NSNumber for everyone to convert, NSNumber itself is a pointer type variable.

Inherits from NSValue : NSObject

Let's have a simple conversion example:

NSUInteger
 count = 1;

NSNumber
 *j = [NSNumber numberWithInt:count];

[ary
 addObject:j];

It's clear, it's time to convert it again when using this value...

Yesterday, I just used the out of order of the array again. I found a Sample online to modify it. The code is as follows:

#pragma
 mark -

#pragma
 mark (NSMutableArray *)randArray:(NSMutableArray *)ary

-
 (NSMutableArray *)randArray:(NSMutableArray *)ary{

  NSMutableArray
 *tmpAry = [NSMutableArray arrayWithArray:ary];

  NSUInteger
 count = [ary count];

  for

(NSUInteger i = 0; i < count; ++i) {

    int

nElements = count - i;

    //
 Seed the random number generator

    srandom(time(NULL));

    int

n = (random() % nElements) + i;

    [tmpAry
 exchangeObjectAtIndex:i withObjectAtIndex:n];

  }

  return

tmpAry;

}

If you have any questions, please leave a message or go to the community of this site to exchange and discuss. Thank you for reading. I hope it can help you. Thank you for your support for this site!