NSString.length 给出 EXC_BAD_ACCESS
我有以下代码:
NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
NSString *temp;
for (int i = 0; i < [array count]; i++)
{
temp = [array objectAtIndex:i];
NSLog(@"temp length = %@", [temp length]);
}
我在 NSLog 行收到 EXC_BAD_ACCESS 错误。我认为它在 [temp length] 位处出错。奇怪的是,我可以在 temp 上执行 NSString 的其他方法,并且它们工作正常,例如 [temp characterAtIndex:0]
。
我也尝试过执行 [[array objectAtIndex:i] keep];
,但这似乎没有帮助。
有谁知道为什么我会收到此错误?
编辑:事实证明它在 NSLog 崩溃,因为它是 %@ 而不是 %lu。真正的问题是我在这篇文章中省略的其他代码。经过一番尝试后,我成功了。
I have the following code:
NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
NSString *temp;
for (int i = 0; i < [array count]; i++)
{
temp = [array objectAtIndex:i];
NSLog(@"temp length = %@", [temp length]);
}
I get an EXC_BAD_ACCESS error at the NSLog line. I assume it's erring out at the [temp length] bit. The weird thing is, I can do other methods of NSString on temp and they work fine, like [temp characterAtIndex:0]
.
I've also tried doing [[array objectAtIndex:i] retain];
, but that doesn't seem to help.
Does anyone know why I'm getting this error?
EDIT: Turns out it was crashing at the NSLog because it was %@ instead of %lu. The real problem was with other code that I had omitted from this post. After playing around with it some more, I got it working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据我的理解,“%@”占位符用于对象指针,“length”返回“NSUInteger”,它不是指针。尝试使用“%lu”而不是“%@”。
From my understanding, the "%@" placeholder is for object pointers, "length" returns "NSUInteger" which is not a pointer. Try "%lu" instead of "%@".
这个(稍微清理过的)版本对我有用:
正如 thg435 提到的,“%@”用于对象指针,所以如果你向它传递任意数字,它将引发内存访问错误。
This (slightly cleaned up) version works for me:
As thg435 mentioned, "%@" is for object pointers, so if you pass it an arbitrary number it will throw a memory access error.