Objective-C 迭代 NSString 来获取字符
我有这个函数:
void myFunc(NSString* data) {
NSMutableArray *instrs = [[NSMutableArray alloc] initWithCapacity:[data length]];
for (int i=0; i < [data length]; i++) {
unichar c = [data characterAtIndex:i];
[instrs addObject:c];
}
NSEnumerator *e = [instrs objectEnumerator];
id inst;
while (inst = [e nextObject]) {
NSLog("%i\n", inst);
}
}
我认为它在 [instrs addObject:c]
处失败。它的目的是迭代 NSString 的十六进制数字。是什么导致这段代码失败?
I have this function:
void myFunc(NSString* data) {
NSMutableArray *instrs = [[NSMutableArray alloc] initWithCapacity:[data length]];
for (int i=0; i < [data length]; i++) {
unichar c = [data characterAtIndex:i];
[instrs addObject:c];
}
NSEnumerator *e = [instrs objectEnumerator];
id inst;
while (inst = [e nextObject]) {
NSLog("%i\n", inst);
}
}
I think it fails at [instrs addObject:c]
. It's purpose is to iterate through the hexadecimal numbers of an NSString. What causes this code to fail?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
unichar
不是一个对象;而是一个对象。它是一个整数类型。NSMutableArray
只能保存对象。如果您确实想将其放入
NSMutableArray
中,则可以将整数值包装在NSNumber
对象中:[instrs addObject:[NSNumber numberWithInt:c]] ;
但是,首先将值填充到数组中有什么意义呢?您知道如何迭代字符串并获取字符,为什么将它们放入数组中只是为了再次迭代它们呢?
另请注意:
A
unichar
is not an object; it's an integer type.NSMutableArray
can only hold objects.If you really want to put it into an
NSMutableArray
, you could wrap the integer value in anNSNumber
object:[instrs addObject:[NSNumber numberWithInt:c]];
But, what's the point of stuffing the values into an array in the first place? You know how to iterate through the string and get the characters, why put them into an array just to iterate through them again?
Also note that:
如果该函数仅用于将字符显示为十六进制值,您可以使用:
这比您的方法更有效(而且,在您的方法中,您永远不会
释放
instrs 数组,因此它会在非垃圾收集环境中泄漏)。如果字符串包含十六进制数字,那么您将需要重复使用
NSScanner
的scanHexInt:
方法,直到返回NO
。If the function is only meant to display the characters as hexadecimal values, you could use:
This is just a little bit more efficient than your approach (also, in your approach you never
release
theinstrs
array, so it will leak in a non-garbage-collected environment).If the string contains hexadecimal numbers, then you will want to repeatedly use an
NSScanner
'sscanHexInt:
method until it returnsNO
.