Reputation: 2950
I would like to be able to write things like:
NSString *foo = ...;
unichar c = foo[i];
but oddly, NSString
doesn't support array indexing via objectAtIndexedSubscript
. Why doesn't it?
To work around this, would it be sensible to implement a category (e.g., NSString+Indexing
) to extend NSString
?
Upvotes: 4
Views: 197
Reputation: 1026
Add a category on NSString with the method:
-(id)objectAtIndexedSubscript:(NSUInteger)idx
{
if(idx >= self.length)
{
return nil;
}
return @([self characterAtIndex:idx]);
}
and call it like this:
unichar c = [foo[i] unsignedShortValue]
Note that c will be 0 both when the character is the null character, or index is out of bounds.
Upvotes: 4