0

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

2 Answers 2

1

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])];
Sign up to request clarification or add additional context in comments.

Comments

1

Actually u have array within array

Replace this line with yours:

NSString *q = [[array objectAtIndex: (arc4random()% [array count] )] objectAtIndex:0];

1 Comment

What issue doe the OP have here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.