Why does NSString not support objectAtIndexedSubscript and how to work?

I would like to write things like:

NSString *foo = ...; unichar c = foo[i]; 

but strangely, NSString does not support indexing an array through objectAtIndexedSubscript . Why is this not so?

To get around this, would it be wise to implement a category (e.g. NSString+Indexing ) for the NSString extension?

+4
source share
1 answer

Add a category to NSString using the method:

 -(id)objectAtIndexedSubscript:(NSUInteger)idx { if(idx >= self.length) { return nil; } return @([self characterAtIndex:idx]); } 

and name it as follows:

 unichar c = [foo[i] unsignedShortValue] 

Note that c will be 0 when the character is a null character, or the index is outside.

+4
source

Source: https://habr.com/ru/post/1492853/


All Articles