只是概念性描述第一:NSArray的到的NSMutableArray作爲隨機堆
我讀從一個文本文件(單詞列表)的輸入,並使用componentsSeparatedByString
方法將這些詞語成NSArray
。這工作。
但我想隨機選擇單詞,然後從數組中刪除它們,以確保每次都有不同的單詞。當然,您不能更改NSArray
的內容。所以......
我複製了NSArray
的內容放入NSMutableArray
和使用它的選擇源。這也適用 - 每個陣列中有269個對象。
要返回從NSMutableArray
我使用下面的代碼字: 陣列筆記記錄被全局 作爲
arrMutTextWords = [[NSMutableArray alloc] init]; //stack for words
arrTextWords = [[NSArray alloc] init]; //permanent store for words
-(NSString*) getaTextWord
{
// if the mutable text word array is empty refill
if ([arrMutTextWords count] == 0){
for (int i = 0 ; i < [arrTextWords count]; i++)
[arrMutTextWords addObject:[arrTextWords objectAtIndex:i]];
}
int i = random() % [arrMutTextWords count];
NSString* ptrWord = [arrMutTextWords objectAtIndex:i];
[arrMutTextWords removeObjectAtIndex:i];
return ptrWord;
}
以上所述方法的調用時的程序崩潰聲明 - 這裏是調用代碼: arrTmp是全局聲明的arrTmp = [[NSArray alloc] init]; // TMP商店話
for (int i = 0 ; i < 4; i++) {
tmpWord = [self getaTextWord];
[arrTmp addObject:tmpWord];
[arrTmp addObject:tmpWord];
}
我在想,從某種程度上arrMutTextWords
刪除字符串是無效的NSArray
- 但我不認爲這會是如何發生的。
請確保在每行代碼之前添加四個空格 - 它看起來像您的一些代碼沒有被StackOverflow編輯控件處理。 – 2010-02-04 20:00:15