Antiokhos
Antiokhos

Reputation: 3055

nsmutablearray objectatindex is null or not

I have problem.

-(NSString*) get_readMessage:(int)index
{
    if ([msg objectAtIndex:index] == NSNotFound) //not Working
        return @"-1";
    return [msg objectAtIndex:index];
}

lets assume [msg count] is 10 and in the program, we call this function with

NSLog(@"%@",[self get_readMessage:11]);

and now we are out of size of array. crashing application. is there way to check such as "msg[11]==mull;" in objective C?

Upvotes: 0

Views: 316

Answers (1)

rmaddy
rmaddy

Reputation: 318884

You need to check the count.

- (NSString*)get_readMessage:(NSUInteger)index {
    if (index >= msg.count) {
        return @"-1";
    } else {
        return msg[index];
    }
}

Also, change the index to NSUInteger.

And standard naming conventions suggest your method should be named more like readMessage:.

Upvotes: 3

Related Questions