随机化单词

时间:2012-05-13 18:14:55

标签: objective-c ios xcode

我正在制作我的第一个iOS应用,我需要一些帮助。 以下是它的工作方式:

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

所以我认为我应该用随机单词创建一个数组,然后在按下按钮时将它们随机化,以便在用户在文本字段中输入的单词后显示一个随机单词。

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

随机化(不知道如何):

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

以下是显示文本字段文本的代码:

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

如果我放label.text = labeltext;然后它会显示用户输入的单词,但我仍然坚持“从数组中显示随机单词”部分。

任何帮助表示赞赏!

2 个答案:

答案 0 :(得分: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 :(得分:0)

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

@property(nonatomic,retain)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.
}