从NSArray获取随机单词很困难

时间:2011-10-18 20:53:05

标签: objective-c ios cocoa-touch

当我建立&运行我的应用程序,它不会生成任何东西。我生成的是单词,然后删除该单词并继续,直到它耗尽所有单词,然后再次重新填充列表。这是代码:

@implementation randomnumbersViewController
@synthesize words;
@synthesize randomArray;
@synthesize array;

-(IBAction)generateNumber:(id)sender {

    NSInteger randomize(id num1, id num2, void *context);
    int rand = arc4random() %2;
    if (rand)
        return NSOrderedAscending;
    else
        return NSOrderedDescending;
}

- (void)resetRandomArray;
{
    [randomArray setArray: array];
    [randomArray sortUsingFunction:random context:NULL];
}

- (NSString*) getRandomWord; {
    if ([randomArray count] ==0)
        return nil;
    NSString* result;
    NSInteger randomIndex = [[randomArray lastObject] intValue];
    [randomArray removeLastObject];
    result = [words objectAtIndex:randomIndex];
    return result;
}

- (void)buildRandomWordArray
{
    NSInteger index;

    NSError *theError;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"words" ofType:@"text"];
    NSString *text = [NSString stringWithContentsOfFile: path
                                               encoding: NSUTF8StringEncoding
                                                  error: &theError];
    self.words = [text componentsSeparatedByString: @"\n"];

    int arraySize = [words count];
    self.array = [NSMutableArray arrayWithCapacity:arraySize];

    //This code fills "array' with index values from 0 to the number of elements in the     "words" array.
    for (index = 0; index<arraySize; index++)
        [array addObject: [NSNumber numberWithInt: index]];
    [self resetRandomArray];

    //for (index = 0; index<=arraySize; index++)
    // NSLog(@ "Random word: %@", [self getRandomWord]);
}

同样,.txt文档必须包含在资源文件夹中才能使其工作,我确实在那里,但没有。有没有人有任何建议,我怎么能真正得到它来生成单词,或为什么它不能正常工作?

1 个答案:

答案 0 :(得分:1)

我不知道如何对数组进行升序或降序排序将对数组进行洗牌,可能是因为它没有。 :)您应该使用此处实现的Fisher-Yates shuffle:What's the Best Way to Shuffle an NSMutableArray?导入该类别,并在可变数组上调用shuffle。