我如何随机化方法?

时间:2015-02-07 15:51:48

标签: ios objective-c iphone xcode

我有4个无效语句,我想将它们随机化,以便一次从4个触发器中随机化。例如,第一个void触发,然后下一次可能第三个void触发,因此第四个。我可以使用arc4random()还是需要另一种方法?

3 个答案:

答案 0 :(得分:3)

当然可以使用arc4Random。 (最好使用arc4random_uniform,正如@JustSid在他的评论中指出的那样。关闭以修复我的示例代码......)有几种方法可以做到这一点。

首先,我的抱怨。不要称之为方法"空洞"。这是不准确和误导的。 (它让你对编程听起来一无所知。)他们的方法。方法开头的括号内的文本告诉您它返回的值类型。如果它没有返回任何内容,那么“" void"是"没什么的C语言符号。"

所以方法:

-(void) foo;

没有参数,也没有返回任何内容,方法:

-(BOOL) bar;

...也没有参数,但它返回一个布尔结果。

第一种方法不是" void"。这是一种不会返回结果的方法。

现在,问你的问题:

你可以这样做:

- (void) foo;
{
  NSLog(@"foo");
}

- (void) bar;
{
  NSLog(@"bar");
}

- (void) foobar;
{
  NSLog(@"foobar");
}

- (void) randomMethod;
{
  int index = arc4random_uniform(3); 
  switch (index)
  {
    case 0:
      [self foo];
      break;
    case 1:
      [self bar];
      break;
    case 2:
      [self foobar];
      break;
   }
}

你也可以使用积木。您可以设置块指针数组,使用arc4random_uniform()来选择数组索引,并从数组中执行适当的块。 (块是对象,因此您可以将它们添加到数组中。)

块和块指针的语法有点难以理解,所以为了简单起见,我不打算写出来。如果您有兴趣,我可以修改我的答案,以显示该如何完成。

答案 1 :(得分:0)

arc4random()非常适合。

int a = arc4random() % 4;
switch (a) {
    case 0:
        [self void0];
        break;
   case 1:
        [self void1];
        break;
    // ...
}

答案 2 :(得分:0)

对于可扩展的解决方案,您可以使用NSSelectorFromString NSSelectorFromString将生成此警告:“performSelector可能导致泄漏,因为其选择器未知”。如果你不能接受警告,那就有solution

NSArray *methods = @[@"method1", @"method2", @"method3", @"method4"];  //add more if needed

int index = arc4random_uniform((int)methods.count);
NSString *selectedMethod = [methods objectAtIndex:index];

SEL s = NSSelectorFromString(selectedMethod);
[self performSelector:s];

-(void)method1
{
    NSLog(@"method1 is called");
}

-(void)method2
{
    NSLog(@"method2 is called");
}

-(void)method3
{
    NSLog(@"method3 is called");
}
-(void)method4
{
    NSLog(@"method4 is called");
}