【发布时间】:2011-09-09 07:37:20
【问题描述】:
我创建了一个名为 numbers 的可变数组,他以随机顺序保存了 20 个不同的数字。 正如我从调试中看到的那样,数据存储在内存中并自动释放。
在我生成数组之后 我必须将数据保存在数组中以备后用,我可以找到解决方法,我需要能够读取数组中的数字,怎么做? 也许是全局 NSMutable 数组?
代码:
我用来生成数组并打乱它的代码是:
/*
Use scrambleArray to scramble any NSMutableArray into random order.
This method is faster than using a sort with a randomizing compare
function, since it scrambles the array
into random order in a single pass through the array
*/
- (void) scrambleArray: (NSMutableArray*) theArray;
{
int index, swapIndex;
int size = (int)[theArray count];
for (index = 0; index<size; index++)
{
swapIndex = arc4random() % size;
if (swapIndex != index)
{
[theArray exchangeObjectAtIndex: index withObjectAtIndex: swapIndex];
}
}
}
/*
randomArrayOfSize: Create and return a NSMutableArray of NSNumbers,
scrambled into random order.
This method returns an autoreleased array. If you want to keep
it, save it to a retained property.
*/
-(NSMutableArray*) randomArrayOfSize: (NSInteger) size;
{
NSMutableArray* result = [NSMutableArray arrayWithCapacity:size];
int index;
for (index = 0; index<size; index++)
[result addObject: [NSNumber numberWithInt: index]];
[self scrambleArray: result];
currentIndex = 0; //This is an instance variable.
return result;
}
- (void) testRandomArray
{
NSInteger size = 20;
int index;
NSInteger randomValue;
NSMutableArray* randomArray = [self randomArrayOfSize: size];
for (index = 0; index< size; index++)
{
randomValue = [[randomArray objectAtIndex: currentIndex] intValue];
NSLog(@"Random value[%d] = %ld", index, randomValue);
currentIndex++;
if (currentIndex >= size)
{
NSLog(@"At end of array. Scrambling the array again.");
[self scrambleArray: randomArray];
}
}
}
现在我希望能够从我的其他方法中获取 randomArray 中的数据。 谢谢, 什洛米
【问题讨论】:
-
创建数组的邮政编码
-
那么当您尝试以其他方法访问它时会出现什么问题?
-
它不存在。我不能使用:X = [[radomArray objectAtIndex:4]intValue];
-
顺便说一句,如果您的加扰数组无偏非常重要(即,如果您正在构建一个扑克应用程序),那么您应该查看 Fisher-Yates 算法。同样简单但在统计上没有偏见。 HTH 戴夫。
标签: objective-c arrays nsmutablearray