Reputation: 45
I am new to Objective-C and learning by trial and error! Please forgive me if this question is somewhat naïve.
I've created an array of images and need to shuffle them. I've used the advice given here:
What's the Best Way to Shuffle an NSMutableArray?
And now I need to implement the method 'shuffle'. I have separate category for my array and its implementation:
@interface theKid : NSObject {
NSMutableArray* _cards;
}
@property(strong, nonatomic, readonly) NSMutableArray *cards;
- (UIImage*) shuffledCard;
@end
But now I can't figure out how to implement 'shuffle':
@implementation theKid
- (NSMutableArray *) cards {
_cards = [[NSMutableArray alloc] initWithObjects:
[UIImage imageNamed:@"One"],
[UIImage imageNamed:@"Two"],
[UIImage imageNamed:@"Three"],
[UIImage imageNamed:@"Four"], nil];
return _cards;
}
- (UIImage*) shuffledCard {
shuffle *cards;
return [cards objectAtIndex:0];
}
@end
This just effects a blank screen when I try to call 'shuffledCard'. Any advice much appreciated.
Upvotes: 0
Views: 87
Reputation: 1242
Hi i have pasted few lines of code below which will Shuffle an NSMutable Array exactly like what you want.
NSMutableArray * _cards = [[NSMutableArray alloc] init];
[_cards addObject:[UIImage imageNamed:@"One.png"]];
[_cards addObject:[UIImage imageNamed:@"Two.png"]];
[_cards addObject:[UIImage imageNamed:@"Three.png"]];
[_cards addObject:[UIImage imageNamed:@"Four.png"]];
[_cards addObject:[UIImage imageNamed:@"Five.png"]];
// Add the below code in the Shuffle Method
NSUInteger count = [_cards count];
for (NSUInteger i = 0; i < count; ++i)
{
NSInteger remainingCount = count - i;
int exchangeIndex = i + arc4random_uniform(remainingCount);
[_cards exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];
UIImage * image = [_cards objectAtIndex:i];
}
Upvotes: 1
Reputation: 15015
Just use this api for shuffling of object exchangeObjectAtIndex:withObjectAtIndex:
Refer this how to shuffle object in NSMutableArray?
Upvotes: 0