Reputation: 141
i'm new to obj-c (this is my first day class eheh) and i'm trying to change a label with a random string from a multidimensional array. plus, every time the button is hitten you switch the array. i know it's a bit odd eheh… this is the IBAction:
UIButton *button = (UIButton *)sender;
NSMutableArray *firstArray = [NSMutableArray array];
[firstArray addObject:@"foo"];
NSMutableArray *secondArray = [NSMutableArray array];
[secondArray addObject:@"bar"];
NSMutableArray *frasi = [NSMutableArray array];
[frasi addObject:firstArray];
[frasi addObject:secondArray];
NSMutableArray *array = [NSMutableArray arrayWithObjects:[frasi objectAtIndex:[button isSelected]], nil];
NSString *q = [array objectAtIndex: (arc4random()% [array count] )];
NSString *lab = [NSString stringWithFormat:@"%@", q];
self.label.text = lab;
all works, but the new label is
( "foo" )
instead of just foo (without quotes)... probably i mess in the last block of code...
ty
Upvotes: 0
Views: 144
Reputation: 38239
Actually u have array within array
Replace this line with yours:
NSString *q = [[array objectAtIndex: (arc4random()% [array count] )] objectAtIndex:0];
Upvotes: 1
Reputation: 6505
So, you create 2 mutable arrays, then add them to a new mutable array frasi
. Then you get one of those two arrays and use it as the single element (because you use arrayWithObjects:
instead of arrayWithArray:
) of a new array array
.
So array
is an array that contains a single array element (instead of an array of strings as you may believe).
When you get an object from array
, it's always the same single object that was used to initialize it: either firstArray
or secondArray
.
So you get an array of strings where you expect a string. When using stringWithFormat:
, the specifier %@
is replaced with the string description of that object.
A string returns itself as its own description. But the description of an array is the list of all its elements separated with commas and surrounded by parenthesis, which is why you get ( "foo" )
.
So instead or creating unneeded arrays, you may just replace all the 8th last lines with this:
NSArray *array = [button isSelected] ? secondArray : firstArray; self.label.text = [array objectAtIndex:arc4_uniform([array count])];
Upvotes: 1