NSString.length 给出 EXC_BAD_ACCESS

发布于 2024-12-11 13:01:31 字数 609 浏览 0 评论 0原文

我有以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一绘本一梦想 2024-12-18 13:01:31

根据我的理解,“%@”占位符用于对象指针,“length”返回“NSUInteger”,它不是指针。尝试使用“%lu”而不是“%@”。

From my understanding, the "%@" placeholder is for object pointers, "length" returns "NSUInteger" which is not a pointer. Try "%lu" instead of "%@".

许久 2024-12-18 13:01:31

这个(稍微清理过的)版本对我有用:

    NSError *error = nil;
    NSString *path = [@"~/Desktop" stringByExpandingTildeInPath];
    NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:
        path error:&error];
    if (error) NSLog(@"%@", error);

    for (NSString *path in array) {
        NSLog(@"Path length = %lu", path.length);
    }

正如 thg435 提到的,“%@”用于对象指针,所以如果你向它传递任意数字,它将引发内存访问错误。

This (slightly cleaned up) version works for me:

    NSError *error = nil;
    NSString *path = [@"~/Desktop" stringByExpandingTildeInPath];
    NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:
        path error:&error];
    if (error) NSLog(@"%@", error);

    for (NSString *path in array) {
        NSLog(@"Path length = %lu", path.length);
    }

As thg435 mentioned, "%@" is for object pointers, so if you pass it an arbitrary number it will throw a memory access error.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文