Friday, May 31, 2013

NSArray objectAtIndexedSubscript example in Objective C (iOS).


NSArray objectAtIndexedSubscript

Returns the object at the specified index.

- (id)objectAtIndexedSubscript:(NSUInteger)idx

Parameters
idx
An index within the bounds of the array.

Return Value
The object located at index.

Discussion of [NSArray objectAtIndexedSubscript]
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.

This method is identical to objectAtIndex:.

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

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

NSArray objectAtIndexedSubscript 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 objectAtIndexedSubscript:0];
NSString *longitudeValue = [subCoordinates objectAtIndexedSubscript:1];

End of NSArray objectAtIndexedSubscript example article.