Objective-c 空 NSArray 错误

发布于 2024-12-04 16:01:31 字数 841 浏览 1 评论 0原文

我正在使用 JSON 将数据解析为 NSArray 'courseArray'。然后,我使用 NSPredicate 过滤这些数据并将其存储到“行”中。问题是,我不知道如何确定“行”是否为空。例如:如果记录存在,行将包含适当的对象,但如果记录不存在,则应用程序崩溃(另外,当我使用 NSLog 查看数组的内容为空时,我相信它应该说它为零?如果没有对象)。我该如何解决这个问题?

if (dict)
{
    courseArray  = [[dict objectForKey:@"lab"] retain];
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"labNumber== %@",labSelected]; //filter
    rows = [[courseArray filteredArrayUsingPredicate:predicate]retain];
}

[jsonreturn release];

self.formattedTextView.opaque = NO;
self.formattedTextView.backgroundColor = [UIColor clearColor];

NSLog(@"array %@",rows);

 **NSDictionary *currentSelection = [rows objectAtIndex:0];** (app crashes at this line - [NSArray objectAtIndex:]: index 0 beyond bounds for empty array')
 NSString *labNumber = [currentSelection objectForKey:@"labNumber"];

I'm using JSON to parse data into an NSArray 'courseArray'. I then filter this data using NSPredicate and store it into 'rows'. The problem is, i dont know how to determine if 'rows' is empty or not. For example : If a record exists, rows will contain the appropriate objects, but if the record doesnt exist then the application crashes (also when i use NSLog to see the contents of the array its blank, i believe its supposed to say its nil? if there are no objects). How can i fix this?

if (dict)
{
    courseArray  = [[dict objectForKey:@"lab"] retain];
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"labNumber== %@",labSelected]; //filter
    rows = [[courseArray filteredArrayUsingPredicate:predicate]retain];
}

[jsonreturn release];

self.formattedTextView.opaque = NO;
self.formattedTextView.backgroundColor = [UIColor clearColor];

NSLog(@"array %@",rows);

 **NSDictionary *currentSelection = [rows objectAtIndex:0];** (app crashes at this line - [NSArray objectAtIndex:]: index 0 beyond bounds for empty array')
 NSString *labNumber = [currentSelection objectForKey:@"labNumber"];

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

强辩 2024-12-11 16:01:31

如果指定索引处没有对象,-objectAtIndex: 将引发异常。如果 rows 为空,则索引 0 处不会有对象,因此会出现异常。由于您没有捕获异常,结果是您的应用程序被终止。

您可能想要将 [rows count] 与 0 进行比较,以检查其中是否有内容,如果没有则做出适当的反应。

-objectAtIndex: will raise an exception if there is no object at the nominated index. If rows is empty there won't be an object at index 0, hence the exception. As you don't catch the exception, the result is that your app is terminated.

You probably want to compare [rows count] to 0 to check that there's something in it and to react appropriately if not.

夜未央樱花落 2024-12-11 16:01:31

尝试 if([courseArray count] > 0) 另一种可以提供帮助的方法是

[courseArray containsObject:(id)]

Try if([courseArray count] > 0) also another method that can be of help here is

[courseArray containsObject:(id)]

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