IOS 开发之 NSMutableArray与NSArray 的区别 首先,来看下2者的区别: NSArray and its subclass NSMutableArray manage collections of objects called arrays. NSArray creates static arrays, and NSMutableArray creates dynamic arrays. N
IOS 开发之 NSMutableArray与NSArray 的区别
首先,来看下2者的区别:
NSArray and its subclass NSMutableArray manage collections of objects called arrays. NSArray creates static arrays, and NSMutableArray creates dynamic arrays.
NSMutableArray是NSArray的子类,NSArray建立静态数组,而NSMutableArray则是动态数组.换句话说,NSArray建立之后不可修改,而NSMutableArray则可以修改.
由于在ObjC中,简单的看下函数addObject,会发现数组的元素是id类型,也就是说是指针.
- (void)addObject:(id)anObject
如此一来数组里就不能压入NSUInteger,BOOL之类的非指针型数据了,要命吧..
那要压入这些内容怎么办呢?对,类型转换,ObjC提供了NSNumber来给大家转换用,NSNumber本身是个指针类型变量.
Inherits from NSValue : NSObject
来个简单的转换例子:
NSUInteger count = 1; NSNumber *j = [NSNumber numberWithInt:count]; [ary addObject:j];
还算明了吧,就是用到这个值的时候又要转换一次,...
昨天刚好又用到数组的乱序,在网上找了个Sample修改了下,代码如下:
#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; }
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!