Until Dec 3rd, 44% off all Manning books, including Barcodes with iOS! Promo code: mobicftw
Our DNA is written in Objective-C

String to Array of Characters

Michael asks:

“How do I split the characters in an NSString into an NSArray? In BASIC I could split a string with empty character, but in Object C this does not work”

One way to do it is to just get one character substrings:

NSString *s = @"Hello World";
int i;
NSMutableArray *m = [[NSMutableArray alloc] init];
for (i=0;i< [s length]; i++)
	[m addObject:[s substringWithRange:NSMakeRange(i, 1)]];
NSLog([m description]);  // most NS* objects have a useful description
[m release];  // don't forget

In Objective C every time you need a starting point and then a length from there it’s call an NSRange. Conveniently there is also a *Make macro for most structures like this. So in this case you just NSMakeRange(position,length) and pass this to a substringWithRange.

Categories: Q&A

%d bloggers like this: