Reputation: 6324
I have a problem. I get an error if the objectAtIndex:x is empty. In my code the user has to insert a code separated by "/" like 32/31/43 or even 32//12. Everything works but if the user insert a single number without the "/" I got the error shown in the picture but I would like to get an alert view that tell the user that the code has been inserted in a wrong format. I hope it's clear. thanks
Upvotes: 1
Views: 3185
Reputation: 4971
For the string "2" componentsSeparatedByString will return an array with only a single object: the string "2".
You are trying to read an object at index 1 (ie the second object), but the array only has one object. It is an error to try to read a value from beyond the end of an NSArray.
It seems like what you're trying to do is require that the value entered has two '/'s so why not check that first?
if ([componentDepthString count] != 3) {
// show an alert and return
}
Upvotes: 0
Reputation: 17906
You can test the number of components in the array with
[componentDepthString count]
Before you go blindly poking into the array, make sure the array has as many elements as you need it to:
// probably a bad idea to name the array with the word "string in it
NSArray *componentDepths = [depthString componentsSeparatedByString:@"/"];
NSInteger numComponents = [componentDepths count];
if(numComponents < 3) {
// show an alert...
return;
}
// otherwise proceed as before
Upvotes: 2
Reputation: 5831
Probably the best way to go about it is to check your array after you created it to make sure there are 3 values.
NSArray *componentDepthString = [depthString componentsSeperatedByString:@"/"];
if ([componentDepthString count] == 3) {
// everything is good and you can continue with your code;
// rest of the code;
} else {
// the user input bad values or not enough values;
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:@"can't continue"
message:@"user input bad values"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:nil];
[myAlert show];
[myAlert release];
}
EDIT: you will have to edit the title and message to say what you want, but that's the basic idea on how to check for bad data before the error and how to display a warning. You will have to add your own logic how to handle it with the user
Upvotes: 2