2013-07-23 41 views
4

我希望能写的东西,如:为什么NSString不支持objectAtIndexedSubscript以及如何解决?

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

,但奇怪的是,NSString通过objectAtIndexedSubscript不支持数组索引。为什么不呢?

要解决此问题,实施类别(例如NSString+Indexing)以扩展NSString是否合理?

+9

但unichar不是一个对象。 – cahn

+0

你看过NSString类的参考吗?你对'unichar c = [string characterAtIndex]'说什么? –

回答

4

上的NSString添加一个类别与方法:

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

    return @([self characterAtIndex:idx]); 
} 

,并调用它像这样:

unichar c = [foo[i] unsignedShortValue] 

注意是c为0时,双方字符是空字符,或索引超出界限。

+0

但是,这是一个明智的解决方案? (OP的问题) –

+0

这不是OP所要求的 – Can

+0

Ohhhhhhhhh ... Duh ...傻了,为什么我没有意识到这一点?......“unichar”不是一个Objective-C对象;因此,'objectAtIndexedSubscript'对'NSString'没有意义。这就是为什么它不支持它,而不能。 –

相关问题