Question

I'd like to have a slider (lets say values from 0 to 4) and an according label which content does NOT display the current slider value BUT an according string.

I'm quite new to Objective-C but here is what I tried (...and did not work ;) )

first I made an Array:

sliderArray = [[NSArray alloc] initWithObjects:
@"sad" @"not so good" @"average" @"good" @"awesome", nil];

then I defined the action:

(IBAction)sliderChange:(id)sender {
   UISlider *slider = (UISlider *) sender;
   NSString *mood = [[NSString alloc] init];
   mood = @"%@", [sliderArray objectAtIndex:(int)[slider value]];
   [sliderLabelMood setText:mood];
}

Xcode can compile but as soon as I try to move the slider it crashes.

Was it helpful?

Solution

The problem is your assignment to the NSString variable mood.

If you use a format string you will have to use the NSString class method stringWithFormat: thus either

mood = [NSString stringWithFormat:@"%@", 
   [sliderArray objectAtIndex:sliderValue]]; 

or

mood = [sliderArray objectAtIndex:sliderValue]; 

Also, you should make sure that the slider value really returns an NSInteger. The normal type for a slider's value property is float. Thus:

NSInteger sliderValue = (NSInteger) slider.value; 

OTHER TIPS

Strings are immutable, so you can reuse the references. Creating one with alloc/init is redundant since it can't be changed after creation. Likewise, you can create arrays that don't require explicit memory management. Note that memory management techniques change with the arrival of ARC in iOS5.

So, try the following to create your array.

sliderArray = [NSArray arrayWithObjects:@"sad", @"not so good", @"average", @"good", @"awesome", nil]; 

and then to show the mood label:

NSInteger index = [slider value];
NSString *mood = [sliderArray objectAtIndex:index];
[sliderLabelMood setText:mood];

You may also consider making your label array static since it's constant and fixed length:

static NSString* moods[] = {
    @"sad", @"not so good", @"average", @"good", @"awesome"
}

In which case you'd change the above code such:

NSInteger index = [slider value];
[sliderLabelMood setText:moods[index]];

If course, you need to be careful that the value of the slide does not exceed the bounds of the moods array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top