来自[NSArray count]的常量错误是无符号的 [英] Constant bugs from [NSArray count] being unsigned
问题描述
由于没有注意到[NSArray count] unsigned
的后果,我一遍又一遍地制造错误。今天的例子相对不寻常:
I'm creating bugs over and over by failing to notice the consequences of [NSArray count] being unsigned
. Today's example is relatively unusual:
for (int i = -1; i < [myArray count]; i++) {
这个循环永远不会执行!你需要(int)[myArray count]
。我通常的错误是:
This loop never executes! You need (int)[myArray count]
. My usual mistake is:
for (int i = 0; i < [myArray count] - 1; i++) {
如果数组为空,则此循环基本上永远执行,因为 [myArray count] -1
溢出 unsigned int
。
If the array is empty, this loop executes basically forever because [myArray count]-1
overflows the unsigned int
.
我尽可能使用快速枚举,但是在这个项目中我经常需要在处理对象时在索引 i-1
和 i + 1
中引用对象我
并且它似乎不适合它。还有其他任何避免这些错误的技巧,除了不那么无能之外吗?
I do use fast enumeration where possible, but in this project I very often need to refer the objects at indexes i-1
and i+1
while processing object i
and it doesn't seem to lend itself to that. Any other tips for avoiding these bugs, other than just being less incompetent?
推荐答案
首先,有一个警告你可以打开拿起这些问题。我认为这是符号比较,命令行标志是 -Wsign-compare
。
Firstly, there's a warning you can turn on to pick up these issues. I think it's "sign comparison", the command line flag is -Wsign-compare
.
如果你想迭代一个数组的元素但是你需要索引,那么最好的方式(在我看来)是 - enumerateObjectsUsingBlock:
If you want to iterate over the elements of an array but you need the index, the neatest way (in my opinion) is -enumerateObjectsUsingBlock:
[myArray enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop)
{
NSlog(@"Object at index %lu is %@", (unsigned long) idx, obj);
if (idx > 0)
{
NSlog(@"Previous object is %@", [myArray objectAtIndex: idx - 1]);
}
if (idx + 1 < [myArray count])
{
NSlog(@"Next object is %@", [myArray objectAtIndex: idx + 1]);
}
}];
这篇关于来自[NSArray count]的常量错误是无符号的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!