Todd Lehman
Todd Lehman

Reputation: 2950

Why doesn't NSString support objectAtIndexedSubscript and how to work around?

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

Answers (1)

cncool
cncool

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

Related Questions