Differences between nsmutablearray and nsarray developed by IOS

Time:2021-12-31

Differences between nsmutablearray and nsarray developed by IOS

First, let’s look at the differences 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 establishes a static array, while nsmutablearray is a dynamic array In other words, nsarray cannot be modified after it is created, while nsmutablearray can be modified

In objc, simply look at the addObject function and 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 data such as nsuinteger and bool can’t be pressed into the array. Damn it

What about pressing in these contents? Yes, for type conversion, objc provides nsnumber for conversion. Nsnumber itself is a pointer type variable


Inherits from NSValue : NSObject

A simple conversion example:


NSUInteger
 count = 1;

NSNumber
 *j = [NSNumber numberWithInt:count];

[ary
 addObject:j];

It’s fairly clear that when this value is used, it has to be converted again

Yesterday, I just used the disordered order of the array. I found a sample on the Internet and modified 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 for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

Recommended Today

Redis featured Q & A

Redis data type type brief introduction characteristic scene String (string) Binary security It can contain any data, such as JPG pictures or serialized objects. One key can store up to 512M It can be used to do the simplest data. It can cache a simple string or a JSON format string. The implementation of redis […]