Showing posts with label NSString. Show all posts
Showing posts with label NSString. Show all posts

Friday, December 31, 2010

Case-insensitive NSSortDescriptor usage

I found this little gem today which was quite useful! If you are using a NSSortDescriptor to sort data using strings, you can make it case insensitive with the following:

sorter = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];

Wednesday, July 21, 2010

Converting NSString to int, float, double, and bool

Here's another really basic & simple NSString tip for today to help you convert strings to various basic types. The NSString class has a bunch of conversions already built in:

float stringFloat = [myString floatValue];
int stringInt = [myString intValue]
double stringDouble = [myString doubleValue]
BOOL boolValue = [myString boolValue];

Easy NSString substring

Sadly, creating a simple substring in Objective-C isn't quite as obvious as in other languages. Here's a basic method to grab a substring of a given string before a defined character, in my case the ":" character:

NSRange end = [_contentsOfElement rangeOfString:@":"];
[myVar setName:[_contentsOfElement substringWithRange:NSMakeRange(0, end.location)]];

If you wanted grab a string between two characters, you could do:

NSRange start = [_contentsOfElement rangeOfString:@"|"];
NSRange end = [_contentsOfElement rangeOfString:@":"];
[myVar setName:[_contentsOfElement substringWithRange:NSMakeRange(start.location, end.location)]];