Search code examples
iphoneobjective-ciosnsarrayrandom-access

Put Random Objects of NSArray To Random UIButtons Title of NSArray


I have an Array with 26 Alphabets and Second Array with 3 UIButtons. I want to take random 3 Alphabets from the Array and Set them randomly As a Titles of 3 UIButtons .here is code.

-(void)placeImages {
     NSMutableArray *alphabetarr=[[NSArray alloc]  
     initWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",
     @"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",nil];
     NSMutableArray *buttons = [NSArray arrayWithObjects:btn1, btn2, btn3, nil];
     for (UIButton *btn in buttons) {
           int randomIndex= arc4random() % [alphabetarr count];
           NSString* titre = [alphabetarr objectAtIndex:randomIndex];
           [btn setTitle:titre forState:UIControlStateNormal]; 
           [alphabetarr removeObjectAtIndex:randomIndex];                        
    }

Through using this code i seen only one alphet in one UIButton..please Suggest any one how Can I pick 3 random alphatbet from an Array and set these 3 random alphabets as Titles of 3 UIButtons of array.


Solution

  • Try this to generate random character. No need to set up an array for that.

    char c = (char)('A' + arc4random_uniform(25))
    

    Refer here.