Friday, December 19, 2008

iPhone Application Development: Objective-C / Cocoa: String Operations

Apple has provided a very nice implementation of the String class. Called NSString. Any string in Objective-C, written as @"Status" is represented in the code as an instance of NSString. Keep in mind that NSString objects are non-mutable. Just like Java String objects.

Go through NSString.h for many many more methods

NSString *nsStr = @"iPhone Development";
int len = [nsStr length]; //
Length of a string
NSString *result = [nsStr stringByAppendingString:anotherNsStr]; Combine 2 strings
NSRange range = [nsStr rangeOfString:@"iPhone"]; // range (not a pointer) would contain location and length of found string
NSString *str = [@"iPhone Application Development" substringFromIndex:7]; // -> Application Development
NSString *str = [@"iPhone Application Development" substringToIndex:6]; // -> iPhone
NSString *str = [@"iPhone Application Development" substringWithRange:NSMakeRange(7, 11)]; // -> Application

NSArray *arrayOfStrings = [@"iPhone Application Development" componentsSeparatedByString:@" "]; // split on space

// Converting between C Strings and NSStrings
NSString *nsStr = [[NSString alloc] initWithUTF8String:"iPhone"];
(const char *)cStr = [nsStr UTF8String];


Mutable Strings: If you need to make modifcations to NSString, use NSMutableString. Some of the valid messages to NSMutableString:


[msMuStr appendString:@" needs an iPhone"];
[msMuStr deleteCharactersInRange:NSMakeRange(7, 11)];
[msMuStr insertString:@" is a good application " atIndex:10];
[msMuStr replaceCharactersInRange:NSMakeRange(7, 11) withString:@" is a good application "];

1 comments:

Дмитрий said...

cool!!!
very helpful!!!!

can you write about Collections. Using of collection is very easy in C#, but in object C - not

Post a Comment