简体   繁体   English

iphone:tableview没有数据时objectAtIndex崩溃

[英]iphone: objectAtIndex crash when tableview have no data

i have the following code 我有以下代码

[[categories objectAtIndex:row]objectForKey:@"name"];

where categories is nsmutablearray .. it is in a tableview but if categories have 0 rows (not null) it gives exception and crash .. the exception is 其中categories是nsmutablearray ..它在tableview中,但如果类别有0行(非null),它会给出异常并崩溃..例外是

Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray objectAtIndex:]: index (0) beyond bounds (0)' 由于未捕获的异常'NSRangeException'而终止应用程序,原因:' - [__ NSCFArray objectAtIndex:]:索引(0)超出边界(0)'

so how can i load the table without throw exception 那么如何加载表而不抛出异常

An empty array will throw this exception if you try to access anything because there is never an object at any index if the array is empty. 如果尝试访问任何内容,则空数组将抛出此异常,因为如果数组为空,则任何索引处都不存在对象。 It's like me not owning a car, but you asking to borrow my car.. you cant borrow my car if I dont have one (then me throwing an exception fist at you for making me realize I'm too poor to own a car) ! 这就像我没有车,但你要借我的车..如果我没有车,你就不能借我的车(然后我向你扔了一个例外的拳头让我意识到我太穷了,不能拥有一辆车) ! =) =)

Do this instead: 改为:

if ([categories count]) {
    [[categories objectAtIndex:row]objectForKey:@"name"];
    ....
}

Edit: 编辑:

Actually, you would probably want to change that if statement to make sure it has at least row + 1 number of objects. 实际上,您可能希望更改if语句以确保它至少有row + 1个对象。

if (([categories count] - 1) >= row) {
    [[categories objectAtIndex:row]objectForKey:@"name"];
    ....
}

错误的是你要求的数组元素不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM