在 Objective-C 中选择 NSArray 的随机元素 [英] 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.
推荐答案
使用此代码:
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.
这篇关于在 Objective-C 中选择 NSArray 的随机元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!