2

In my view, i have 12 buttons,and a array contains 6 names , i want to print the array names in UIButton title. Here's my code:

texts = [[NSMutableArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",nil];
UIButton *button;
NSString *name;
NSUInteger count = [texts count];
int i=0;

for(UIView *view in self.view.subviews)
{
    if([view isKindOfClass:[UIButton class]])
    {
        button= (UIButton *)view;
        if(button.tag >= 1||button.tag <= 20)
        {
            int value = rand() % ([texts count] -1) ;
            int myTag= i+1;
            button = [self.view viewWithTag:myTag];
            name=[NSString stringWithFormat:@"%@",[texts objectAtIndex:value]];
            [button setTitle:name forState:UIControlStateNormal];
            NSLog(@"current  name :%@",name);
        }
        i++;
    }

}
[super viewDidLoad];

The problems I am facing are:

  1. While shuffling the values are repeating,i tried with What's the Best Way to Shuffle an NSMutableArray?, its not working.

  2. I want 6 titles in 12 button that means each title will be in 2 buttons. Please help me solve this issue. What changes should I make?

Community
  • 1
  • 1
Fazil
  • 1,390
  • 2
  • 13
  • 26
  • 1. You have 8 labels in your array, not 6. You randomly pick a title from your array, but then did not remove the title from the list of choices, so you can get duplicates. – futureelite7 Nov 05 '12 at 06:59
  • @futureelite7 what change should i made for remove the title from the list of choices, – Fazil Nov 05 '12 at 07:00
  • What do you want to do? I am not 100% sure I understand your question. – futureelite7 Nov 05 '12 at 07:02
  • i want to display the 6 titles(i update the quest) in 12 buttons,each title in 2 buttons, in random order @futureelite7 – Fazil Nov 05 '12 at 07:03
  • @futureelite7 I think it will be helpful if you explain how to remove the item from array and probably why it needs to be done, I'm sure that will be an accepted answer :) – A-Live Nov 05 '12 at 07:04
  • @fasilmoham, Check with my answer and let me know. – iDev Nov 05 '12 at 07:14

2 Answers2

2

Basically you need to separate the shuffling logic from adding name to button feature. So first shuffle the array and then set the name of buttons.

[super viewDidLoad]; //Always super call should be the first call in viewDidLoad
texts = [[NSMutableArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6", @"1",@"2",@"3",@"4",@"5",@"6", nil];
//adding all 12 button titles to array, use your own logic to create this array with 12 elements if you have only 6 elements

NSUInteger count = [texts count];

for (NSUInteger i = 0; i < count; ++i) {
        // Select a random element between i and end of array to swap with.
        NSInteger nElements = count - i;
        NSInteger n = (arc4random() % nElements) + i;
        [texts exchangeObjectAtIndex:i withObjectAtIndex:n];
}

UIButton *button = nil;
NSString *name = nil;
int i = 0;

for(UIView *view in self.view.subviews)
{
    if([view isKindOfClass:[UIButton class]])
    {
        button= (UIButton *)view;
        if(button.tag >= 1 && button.tag <= 20)
        {
            name = [NSString stringWithFormat:@"%@",[texts objectAtIndex:i]];
            //assuming that the above texts array count and number of buttons are the same, or else this could crash
            [button setTitle:name forState:UIControlStateNormal];
            NSLog(@"current  name :%@",name);
            i++;
        }
    }
}
iDev
  • 23,310
  • 7
  • 60
  • 85
  • Let me clarify (I have a feeling that's needed), in this solution the `used` names are moved to the beginning of array and the next name will be picked from the `unused` variants which are all after the `used` names position. What futureelite7 suggested is to remove the `used` names not to use them again in order to avoid repeating, this way you'd have only 'unused' names at the array during the next iteration. – A-Live Nov 05 '12 at 07:28
  • @A-Live, I am sorry, I didnt get what you meant here. What this code will do is, simply shuffle the array each time we call this method and set the button names to the shuffled values. From fasilmoham's previous question, this is the solution he wanted I guess. Check the comments here http://stackoverflow.com/questions/13206426/how-to-shuffle-nsmutablearray-without-repetition?lq=1 – iDev Nov 05 '12 at 07:33
  • @ACB ITS SHOWING ERROR : `Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIView setTitle:forState:]: unrecognized selector sent to instance ` – Fazil Nov 05 '12 at 07:36
  • @fasilmoham, Number of items in texts array and number of buttons are same as mentioned in my comments? Can you confirm that? Also check it is a button and not any other view on which you are trying to set title. Use my code exactly as it is or try with your code once and confirm. – iDev Nov 05 '12 at 07:38
  • 1
    While copying you probably missed the check `if([view isKindOfClass:[UIButton class]])` which is critically important. @ACB This explanation was certainly not for you, as I think he has hard times understanding the algorithm itself so I've added a little explanation. – A-Live Nov 05 '12 at 07:41
  • @A-Live, Thanks for clarifying that. Also thanks for adding that comment to explain the algorithm. I got confused actually. Sorry for that. – iDev Nov 05 '12 at 07:44
  • @A-Live i copired the code propely still it showing the same error – Fazil Nov 05 '12 at 08:38
  • @fasilmoham, Can you try with your code once and see if it runs? Basically the title setting part is same as your code and hence it should run fine. – iDev Nov 05 '12 at 08:40
  • @ACB i confirmed and made equal number of array item and button still its showing the same error – Fazil Nov 05 '12 at 08:42
  • @fasilmoham, I have removed two lines from this code and updated the answer, please check with this. This will work. There was no need to reassign the button inside the if condition, which I forgot to notice while copying from your code since it worked for you. Basically your tag property of 1 to 20 is not only set for buttons but also for other views, that is why it was crashing. – iDev Nov 05 '12 at 08:42
  • @ACB big big big thanks, its working properly but nw problem with one button,that i want to go home,if i added the home button its showing error,what should i do bro – Fazil Nov 05 '12 at 08:50
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/19077/discussion-between-acb-and-fasil-moham) – iDev Nov 05 '12 at 08:50
1

Make Category of NSMutableArray

@implementation NSMutableArray (ArrayUtils)
- (void)shuffle{
static BOOL seeded = NO;
if(!seeded)
{
    seeded = YES;
    srandom(time(NULL));
}
NSUInteger count = [self count];
for (NSUInteger i = 0; i < count; ++i) {
    // Select a random element between i and end of array to swap with.
    int nElements = count - i;
    int n = (random() % nElements) + i;
    [self exchangeObjectAtIndex:i withObjectAtIndex:n];
}
}
@end
SachinVsSachin
  • 6,401
  • 3
  • 33
  • 39