Friday, May 31, 2013

NSArray objectAtIndex example in Objective C (iOS).


NSArray objectAtIndex

Returns the object located at index.

- (id)objectAtIndex:(NSUInteger)index

Parameters
index
An index within the bounds of the array.

Return Value
The object located at index.

Discussion of [NSArray objectAtIndex]
If index is beyond the end of the array (that is, if index is greater than or equal to the value returned by count), an NSRangeException is raised.

NSArray objectAtIndex example.
if(i<=[array count]){
    if([array objectAtIndex:i]!= nil)
    {
    NSLog("Object present");
    }
    else{
    NSLog("Object Not Present")
    }
}

Example of [NSArray objectAtIndex].
for (int i = 0; i < 6; i ++) {
    if ([array objectAtIndex:i] == [NSNull null]) {
        NSLog(@"object at index %i has no data", i);
    }
}

NSArray objectAtIndex example.
NSString *latitudeValue = [subCoordinates objectForKey:@"0"];
NSString *longitudeValue = [subCoordinates objectForKey:@"1"];

But if the JSON decoding worked, subCoordinates would be an NSArray object and you would have to use this code instead:

NSString *latitudeValue = [subCoordinates objectAtIndex:0];
NSString *longitudeValue = [subCoordinates objectAtIndex:1];

End of NSArray objectAtIndex example article.