Objective-c 空 NSArray 错误
我正在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果指定索引处没有对象,
-objectAtIndex:
将引发异常。如果rows
为空,则索引 0 处不会有对象,因此会出现异常。由于您没有捕获异常,结果是您的应用程序被终止。您可能想要将
[rows count]
与 0 进行比较,以检查其中是否有内容,如果没有则做出适当的反应。-objectAtIndex:
will raise an exception if there is no object at the nominated index. Ifrows
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.尝试 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)]