【问题标题】:Why doesen't the number 2 work in this for-loop?为什么数字 2 在这个 for 循环中不起作用?
【发布时间】:2011-02-12 01:15:00
【问题描述】:

我有一个函数通过数组中的每个元素运行。 很难解释,所以我把代码贴在这里:

NSLog(@"%@", arraySub);

for (NSNumber *favoriteThing in arrayFav){  

    int favoriteLoop = [favoriteThing intValue] + favCount;
    NSLog(@"%d", favoriteLoop);

    id arrayFavObject = [array objectAtIndex:favoriteLoop];
    [arrayFavObject retain];
    [array removeObjectAtIndex:favoriteLoop];
    [array insertObject:arrayFavObject atIndex:0];
    [arrayFavObject release];

    id arraySubFavObject = [arraySub objectAtIndex:favoriteLoop];
    [arraySubFavObject retain];
    [arraySub removeObjectAtIndex:favoriteLoop];
    [arraySub insertObject:arraySubFavObject atIndex:0];
    [arraySubFavObject release];

    id arrayLengthFavObject = [arrayLength objectAtIndex:favoriteLoop];
    [arrayLengthFavObject retain];
    [arrayLength removeObjectAtIndex:favoriteLoop];
    [arrayLength insertObject:arrayLengthFavObject atIndex:0];
    [arrayLengthFavObject release];

}

NSLog(@"%@", arraySub);

数组arrayFav 包含这些数字:3, 8, 2, 10, 40。 数组 array 包含 92 个带名称的字符串。 数组arraySub 包含数字091,表示带有来自数组array 的标题的文件名。 数组arrayLength包含92个字符串,代表数组arraySub中每个文件的大小。

现在,第一个 NSLog 正如预期的那样显示数字 0 到 91。 循环中的NSLog-s 显示数字3, 8, 2, 10, 40,也符合预期。

但奇怪的是:最后一个 NSLog 显示了这些数字: 40, 10, 0, 8, 3, 1, 2, 4, 5, 6, 7, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91

即 40、10、0、8、3 等等。

里面不应该是0,应该是2..

您知道为什么会发生这种情况或有解决方法吗?谢谢。

编辑:代码已更改。 arrayFav 现在包含数字。

【问题讨论】:

  • 在 for 循环中尝试 CFShowStr(string);
  • 看起来你的“2号”实际上是@"0x64356f8"
  • 也许你应该将结果粘贴到支持换行符的地方:(.
  • @KennyTM:是的。无论如何,这不再重要了,因为arrayFav 现在包含数字。检查主要问题。

标签: iphone arrays for-loop


【解决方案1】:

-intValue 方法返回 0 if there is something funky 关于被转换字符串的开头。

不要使用NSString 来存储整数,而是尝试使用NSNumber 来强制在您的数组中存储数字,或者调试正在发送的-intValue 消息。

【讨论】:

  • 引用:Now, the first NSLog shows, as expected, the numbers 0 to 91. The NSLog-s in the loop shows the numbers 3, 8, 2, 10, 40, also as expected.
  • 使用NSNumber 保存无符号整数可能更容易调试。
  • 是的。但是数组从 plist 加载数据,这不是很头疼吗?
  • 不,这并不令人头疼,因为您可以将 plist 中的数字存储为“数字”,这意味着它将为您加载为 NSNumber
  • 我不这么认为,因为 plist 文件支持存储 NSNumber 实例:cf。 en.wikipedia.org/wiki/Property_list#Mac_OS_X
【解决方案2】:

我通过删除 for 循环并在 arraySub 中搜索正确的位置来解决此问题。

// If the object is not really the object we want, get what we want
if (favoriteLoop != [[[arraySub objectAtIndex:favoriteLoop] description] intValue]){
    favoriteLoop = [arraySub indexOfObject:[NSString stringWithFormat:@"%d", favoriteLoop]];
}         

【讨论】:

    猜你喜欢
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 2023-01-28
    • 2010-10-17
    相关资源
    最近更新 更多