Apologies for such a newbie question.
I have written a class method that takes three strings and returns a substring.
I have written conditional statements that only allow the substring to returned if certain criteria are met. However I am unsure what I need to return if the substring cannot be extracted. At the moment I have the method returning a default 'error' string, but I have the feeling that this may not be best practice.
Here is my method:
+(NSString *)ExtractSubstringFrom:(NSString *)sourceString
Between:(NSString *)firstString And:(NSString *)secondString {
NSRange stringRangeOne = [sourceString rangeOfString:secondString];
NSString *resultString;
if (stringRangeOne.location != NSNotFound) {
resultString = [sourceString substringToIndex:stringRangeOne.location];
}
NSRange stringRangeTwo = [sourceString rangeOfString:firstString];
if (stringRangeTwo.location !=NSNotFound) {
resultString = [resultString substringFromIndex:stringRangeTwo.location+stringRangeTwo.length];
return resultString;
}
else return @"Error!";
//To do... improve error checking
}
How can I make this method more error friendly?
There are several ways of handling errors of this kind in Objective C:
nil
. Since performing operations on nil
objects is allowed in Objective C, this is relatively safe.NSError
objects - this is more typical of errors that can be addressed by end users, such as connection and configuration problems. The unfortunate side effect of this kind of API is the need to set up and pass an extra parameter.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With