挑选的NSArray的随机元素在Objective-C [英] Pick random element of NSArray in Objective-C
问题描述
可能重复:结果
采摘一个NSArray 随机对象
我在Objective-C的使用字符串数组:
I have have an array in Objective-C with strings:
NSArray *tips;
tips = [NSArray arrayWithObjects:
@"Foo",
@"Bar",
@"Baz",
nil];
我想这需要从阵列中随机项目,并将其返回的方法。有没有一种方法,或者我怎么能写一个自己?谢谢你。
I want a method that takes a random item from the array, and returns it. Is there a method, or how can I write one myself? Thanks.
推荐答案
使用此code:
uint32_t rnd = arc4random_uniform([tips count]);
NSString *randomObject = [tips objectAtIndex:rnd];
编辑:
虽然在我的项目上工作,我决定创建的NSArray一个类别。这很简单,但我发现它是有用的。
While working on my project i decided to create a category for NSArray. It's very simple but i found it useful.
下面是文件:
的NSArray + Random.h
#import <Foundation/Foundation.h>
@interface NSArray (Random)
- (id)randomObject;
@end
的NSArray + Random.m
#import "NSArray+Random.h"
@implementation NSArray (Random)
-(id)randomObject {
NSUInteger myCount = [self count];
if (myCount)
return [self objectAtIndex:arc4random_uniform(myCount)];
else
return nil;
}
@end
然后在当前的例子中,你使用它是这样的:
Then in the current example you use it like this:
NSString *randomObject = [tips randomObject];
使用类还有一个好处:当你决定要改变你在你的应用程序选择随机对象,你只需要修改randomObject方法方式
Using category has another advantage: when you decide to change your way of selecting random objects in your app you just modify the randomObject method.
这篇关于挑选的NSArray的随机元素在Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!