Random NSNumber from array
开发者_如何学JAVAI'm trying to make an IBAction pick a random float from an NSMutableArray
(10.00, 2.56, 4.25, 1.95).
Here's what I tried:
In the viewDidLoad:
NSMutableArray *numberPicker = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:10.00],
[NSNumber numberWithFloat:2.56],
[NSNumber numberWithFloat:4.25],
[NSNumber numberWithFloat:1.95],
nil];
In the IBAction:
-(IBAction)buttonPressed: (id)sender{
result = [numberPicker objectAtIndex:arc4random() % [numberPicker count])];
Obviously this isn't working, i get an error "Assigning to 'float' from incompatible type 'id'". Any ideas how to get one of the numbers into "result"?
You just change one line to:
result = [[numberPicker objectAtIndex:arc4random() % [numberPicker count])] floatValue];
You could write a method randomElement
in a category on NSArray
#import "NSArray+RandomUtils.h"
@implementation NSArray (RandomUtils)
-(id)randomElement
{
if ([self count] < 1) return nil;
NSUInteger randomIndex = arc4random() % [self count];
return [self objectAtIndex:randomIndex];
}
@end
or just use the one, I wrote.
You will use it like this:
#import "NSArray+RandomUtils.h"
Use a property numberPicker
@property (retain) NSArray *numberPicker
viewDidLoad:
self.numberPicker = [NSArray arrayWithObjects: [NSNumber numberWithFloat:10.00], [NSNumber numberWithFloat:2.56], [NSNumber numberWithFloat:4.25], [NSNumber numberWithFloat:1.95], nil];
in your
buttonPressed:
useresult = [(NSNumber *)[self.numberPicker randomElement] floatValue];
精彩评论