Ios 我如何随机化方法?
我有4个void语句,我想把它们随机化,这样每次4个触发器中就有一个触发器。例如,第一个void触发,下一次可能第三个void触发,第四个。我可以使用arc4random()还是需要另一种方法Ios 我如何随机化方法?,ios,objective-c,iphone,xcode,Ios,Objective C,Iphone,Xcode,我有4个void语句,我想把它们随机化,这样每次4个触发器中就有一个触发器。例如,第一个void触发,下一次可能第三个void触发,第四个。我可以使用arc4random()还是需要另一种方法 arc4random()非常适合这样做 int a = arc4random() % 4; switch (a) { case 0: [self void0]; break; case 1: [self void1]; brea
arc4random()
非常适合这样做
int a = arc4random() % 4;
switch (a) {
case 0:
[self void0];
break;
case 1:
[self void1];
break;
// ...
}
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");
}
当然可以使用arc4Random。(正如@JustSid在他的评论中指出的那样,最好使用arc4random_uniform。请关闭以修复我的示例代码…)实现这一点的方法几乎是无限的 首先是我的抱怨。不要将方法称为“voids”。这是不准确和误导的。(这让你听起来对编程一无所知。)它们是方法。方法开头括号内的文本告诉您它返回的值的类型。如果它没有返回任何内容,那么单词“void”就是C语言中表示“nothing”的符号 因此,该方法:
-(void) foo;
-(BOOL) bar;
不接受任何参数,也不返回任何内容,其中方法:
-(void) foo;
-(BOOL) bar;
…也不接受任何参数,但它返回布尔结果
第一种方法不是“无效”。它是一个不返回结果的方法
现在,回答你的问题:
你可以这样做:
- (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()拾取数组索引,并从数组中执行适当的块。(块是对象,因此可以将其添加到阵列。)
块和块指针的语法有点难理解,所以为了简单起见,我不打算写出来。如果您感兴趣,我可以修改我的答案,以说明如何做到这一点。对于可扩展的解决方案,您可以使用
nsselector或fromstring
NSSelectorFromString
将生成以下警告:“performSelector可能会导致泄漏,因为其选择器未知。”。如果你不能接受警告,那就没有理由了
int a = arc4random() % 4;
switch (a) {
case 0:
[self void0];
break;
case 1:
[self void1];
break;
// ...
}
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");
}
不太可能,两种方法都会提供类似的结果。除了如果最大数不是除法器的倍数,则使用模将导致非均匀分布。@JustSid,这一点很好。(我使用
arc4random_uniform()编辑了我的答案以显示)
相反。你可以通过让它从数组中随机选择一个方法选择器来保存代码,但这里的一些其他解决方案可以。有一个抱怨:说void
是一种无中生有的C-ism会让人们在以后需要使用void指针时感到困惑。没错。void指针是一匹不同颜色的马,这就是void*
(一种我从来都不喜欢的语法。我更喜欢像unknown*
)但是没有人说C很漂亮,或者很容易阅读。我的岳父说“C是一种只写的语言。”虽然这样做显然是为了节省关键字,但以这种方式重用void
只会让人感到困惑。。。