【问题标题】:Randomize words随机化单词
【发布时间】:2012-05-13 18:14:54
【问题描述】:

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

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

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

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

随机化(虽然不知道如何):

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

这里是显示文本字段中文本的代码:

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

如果我输入label.text = labeltext;,那么它会显示用户输入的单词,但我被困在“显示数组中的随机单词”部分。

任何帮助表示赞赏!

【问题讨论】:

标签: objective-c ios xcode


【解决方案1】:
    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 就完美了。没有它你会得到一个 indexerror。
  • 它给了我一个错误 - 二进制表达式的操作数无效('u_int32_t(*)(void)' 和 'NSUnteger'(又名 'unsigned int'))
  • 不,@Martol1ni 是正确的; arc4random() % [words count] 的范围是 0 到 count-1,这正是数组的有效索引范围。另外,不是arc4random,而是arc4random()(它是一个函数)。另外,使用arc4random_uniform([words count]) 代替模数。
  • @JacquesCousteau 感谢您的指出,问题已锁定编辑
  • 完美运行。现在只需要弄清楚如何使它们不可重复:) 特别感谢 zahreelay。
【解决方案2】:

给 OP。要使随机答案不重复,请将您的数组设置为视图控制器的 viewDidLoad 中的实例变量。同时创建一个属性剩余单词:

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

【讨论】:

    猜你喜欢
    • 2014-07-24
    • 2019-07-12
    • 2018-04-11
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多