Felipe Xavier
Felipe Xavier

Reputation: 165

How to solve this " index 0 beyond bounds for empty array! "

I am having a problem when checking if there is something coming from database:

Code:

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!!!");
}

my query:

-(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;
}

The error appears when I check whether it is empty or if something is returned.

Upvotes: 3

Views: 3927

Answers (4)

Jiri Zachar
Jiri Zachar

Reputation: 597

Or use block in function :)

-(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");
    }
}

and call

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);
}];

Upvotes: -1

Rohan
Rohan

Reputation: 2935

You need to check result as :

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

Hope this will help.

Upvotes: 2

andreamazz
andreamazz

Reputation: 4286

test[0] is already trying to subscript the array. You need to check for the count property:

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

Upvotes: 4

chiarotto.alessandro
chiarotto.alessandro

Reputation: 1589

replace test[0] with

test.count > 0

Upvotes: 5

Related Questions