如何解决这个问题"索引0超出空数组的边界! "

时间:2015-12-14 13:17:28

标签: ios objective-c nsarray

我在检查是否有来自数据库的内容时遇到问题:

代码:

hourPrograma: @"12:00";
NSArray *hourLinha = [hourProgram componentsSeparatedByString:@":"];

NSArray * test = [notificationDAO selectHourMin:[hourLinha[0] intValue]:[hourLinha[1] intValue]];

if (!test[0]) {
   NSLog(@"ok!!!");
} else {
   NSLog(@"empty!!!");
}

我的疑问:

-(NSArray *) selectHourMin:(NSInteger *) hour: (NSInteger *) min {
    query = [NSString stringWithFormat:@"SELECT hour, min FROM notification WHERE %i = hour AND %i = min", hour, min];
    NSArray * resp = [self loadDataFromDB:query];
    return resp;
}

当我检查它是否为空或是否返回某些内容时,会出现错误。

4 个答案:

答案 0 :(得分:5)

替换test [0]
test.count > 0

答案 1 :(得分:4)

test[0]已经在尝试下标数组。您需要检查count属性:

if (test.count) {
    // ...
}

答案 2 :(得分:2)

您需要将结果检查为:

if (test.count > 0) 
{    
  NSLog(@"ok!!!"); 
} 
else 
{    
  NSLog(@"empty!!!"); 
}

希望这会有所帮助。

答案 3 :(得分:-1)

或者在功能中使用块:)

-(void) selectHourMin:(NSInteger *) hour: (NSInteger *) min success:(void (^)(NSArray *result))successBlock failure:(void (^)(NSString * error))failureBlock{
    query = [NSString stringWithFormat:@"SELECT hour, min FROM notification WHERE %i = hour AND %i = min", hour, min];
    NSArray * resp = [self loadDataFromDB:query];

    if (resp.count > 0 ) {
        successBlock(resp);
    }else{
    failureBlock(@"empty result");
    }
}

并致电

hourPrograma: @"12:00";
NSArray *hourLinha = [hourProgram componentsSeparatedByString:@":"];

NSArray * test = [notificationDAO selectHourMin:[hourLinha[0] intValue]:[hourLinha[1] intValue]];

[self selectHourMin:1 :2 success:^(NSArray *result) {
    NSLog(@"result: %@", result);
} failure:^(NSString *error) {
    NSLog(@"%@", error);
}];