2012-05-13 104 views
0

我正在制作我的第一个iOS应用程序,需要一些帮助。 这是它将如何工作:随机词汇

用户在文本框中输入单词,按下按钮,并在标签中它应该是这样的: [Users word] [Randomly picked word]

所以我认为我应该做的阵列与随机单词,然后莫名其妙地当按下按钮,在文本字段中输入的用户的话后显示一个随机单词了许多的随机他们。

但是,它应该如何运作? 这里是我的想法是:

随机本(不知道怎么虽然):

NSArray *words = [NSArray arrayWithObjects: @"Blue", @"Green", @"Red", nil ]; 

,这里是从文本框显示文本代码:

NSString *labeltext = [NSString stringWithFormat:@"%@", [textField text]]; 

如果我把label.text = labeltext;,然后它显示用户键入的单词,但我卡在“显示随机单词从数组”部分。

任何帮助表示赞赏!

+0

可能重复[阅读从随机值一个数组](http://stackoverflow.com/questions/7047085/reading-random-values-from-an-array);另请参见[在NSArray中选择一个随机对象](http://stackoverflow.com/questions/3318902/picking-a-random-object-in-an-nsarray) –

+0

这应该有所帮助:http://stackoverflow.com/a/56656/679254 – modocache

回答

3
NSArray *words = [NSArray arrayWithObjects: @"Blue", @"Green", @"Red", nil ]; 
    NSString *str=[words objectAtIndex:arc4random()%[words count]]; 
    // using arc4random(int) will give you a random number between 0 and int. 
    // in your case, you can get a string at a random index from your words array 
+1

降-1,这是完美的。没有它你会得到一个索引错误。 – Martol1ni

+0

它给了我一个错误 - 无效的操作数到二进制表达式('u_int32_t(*)(void)'和'NSUnteger'(又名'无符号整型')) – figdig

+0

不能,删除-1可能会给indexOutOfBounds错误.. – zahreelay

0

给OP。为了使随机答案不重复,在你的视图控制器的viewDidLoad中将你的数组设置为一个实例变量。还创建一个属性remainingWords:

@属性(非原子,保留)的NSMutableArray * remainingWords;

您的viewDidLoad代码应该是这样的:

-(void) viewDidLoad; 
{ 
    //Create your original array of words. 
    self.words = [NSArray arrayWithObjects: @"Blue", @"Green", @"Red", nil ]; 

    //Create a mutable copy so you can remove words after choosing them. 
    self.remainingWords = [self.words mutableCopy]; 
} 

然后,你可以写这样的方法来从你的阵列获得唯一的一句话:中

- (NSString *) randomWord; 
{ 
    //This code will reset the array and start over fetching another set of unique words. 
    if ([remainingWords count] == 0) 
    self.remainingWords = [self.words MutableCopy]; 

    //alternately use this code: 
    if ([remainingWords count] == 0) 
    return @""; //No more words; return a blank. 
    NSUInteger index = arc4random_uniform([[remainingWords count]) 
    NSString *result = [[[remainingWords index] retain] autorelease]; 
    [remainingWords removeObjectAtindex: index]; //remove the word from the array. 
}