for (NSArray *a in directory) 无法按我的预期工作
将 plist 加载到 NSArray 后,我尝试访问其嵌套数组。
NSArray *tree = [[NSArray alloc] initWithContentsOfFile:path];
for (NSArray *a in tree)
{
//Let's assume object at index 0 is always NSString
NSLog(@"Returning the string: %@ ", [a objectAtIndex:0]);
}
来自调试器的一些值:
tree __NSCFArray * 0x6856cf0
0 __NSCFString * 0x6818b70
1 __NSCFString * 0x682be10
2 __NSCFArray * 0x6856cd0
所以我期望 for 语句跳过前 2 个 NSString,然后使用 NSArray 执行。
然而单步执行一行: a __NSCFString * 0x6818b70
然后繁荣,应用程序崩溃。
尖端?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不是 for (NSArray *a in tree) 表达式的作用。该语句创建一个名为
a
且类型为NSArray *
的局部变量,并将其指定为引用tree
中的每个对象,无论该对象是否位于 a特定索引是否为 NSArray。您的快速枚举循环大致相当于:
http://developer. apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/Chapters/ocFastEnumeration.html
That is not what the
for (NSArray *a in tree)
expression does. That statement creates a local variable nameda
of typeNSArray *
and assigns it to reference each object intree
, regardless of if the object at a particular index is an NSArray or not.Your fast enumeration loop is roughly equivalent to:
http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/Chapters/ocFastEnumeration.html
正如乔纳(Jonah)已经指出的那样,仅仅告诉编译器您期望一个 NSArray 并不能真正使其成为一个。如果您想跳过循环中不是数组的对象,可以按如下方式执行:
As Jonah already pointed out, just telling the compiler that you expect an
NSArray
doesn't actually make it one. If you want to skip objects that aren't arrays in your loop, you could do it as follows:作为 omz & Jonah 指出您的
for
循环并不只是通过指定a
的类型来选择项目。这是另一种变体,它清楚地表明元素可能不是数组:As omz & Jonah have pointed out your
for
loop does not also select items simply by specifying the type ofa
. Here is another variation which makes it clear the elements may not be arrays: