Friday, May 31, 2013

NSArray indexOfObject inRange example in Objective C (iOS).

NSArray indexOfObject inRange

Returns the lowest index within a specified range whose corresponding array value is equal to a given object .

- (NSUInteger)indexOfObject:(id)anObject inRange:(NSRange)range

Parameters of [NSArray indexOfObject inRange]
An object.
The range of indexes in the array within which to search for anObject.

Return Value
The lowest index within range whose corresponding array value is equal to anObject. If none of the objects within range is equal to anObject, returns NSNotFound.

Discussion of [NSArray indexOfObject inRange]
Starting at index 0, each element of the array is sent an isEqual: message until a match is found or the end of the array is reached. This method passes the anObject parameter to each isEqual: message. Objects are considered equal if isEqual: returns YES.

This method raises an NSRangeException exception if the range parameter represents a range that doesn’t exist in the array.

NSArray indexOfObject inRange example.
@interface NSArray (indexesOfObject)
-(NSIndexSet *)indexesOfObject:(id)target;

@implementation NSArray (indexesOfObject)
-(NSIndexSet *)indexesOfObject:(id)target {
    NSRange range = NSMakeRange(0, [self count]);
    NSMutableIndexSet *indexes = [[NSMutableIndexSet alloc] init];
    NSUInteger idx;
    while (range.length && NSNotFound != (idx = [self indexOfObject:target inRange:range])) {
        [indexes addIndex: idx];
        range.length -= idx + 1 - range.location;
        range.location = idx + 1;
    return [indexes autorelease];

Example of [NSArray indexOfObject inRange].
NSArray *copy = [mutableArray copy];
NSInteger index = [copy count] - 1;
for (id object in [copy reverseObjectEnumerator]) {
    if ([mutableArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound) {
        [mutableArray removeObjectAtIndex:index];
[copy release];

NSArray indexOfObject inRange example.
    NSArray *arrayList
    NSString *seccoad
    int i = [arrayList indexOfObject:seccoad];
    NSUInteger location;
    NSUInteger length;
    while (1) {
        NSRange temp_range;
        temp_range.location = i + 1;
        temp_range.length = 0;
        i = [arrayList indexOfObject:seccoad inRange:temp_range];
        if (i == 0) {

End of NSArray indexOfObject inRange example article.