Saturday, June 1, 2013

NSMutableArray setObject atIndexedSubscript example in Objective C (iOS).


NSMutableArray setObject atIndexedSubscript

Replaces the object at the index with the new object, possibly adding the object.

- (void)setObject:(id)anObject atIndexedSubscript:(NSUInteger)index

Parameters
anObject
The object with which to replace the object at index index in the array. This value must not be nil.
Important: Raises an NSInvalidArgumentException if anObject is nil.
index
The index of the object to be replaced. This value must not exceed the bounds of the array.
Important: Raises an NSRangeException if index is beyond the end of the array.

Discussion of [NSMutableArray setObject atIndexedSubscript]
If the index is equal to count the element is added to the end of the array, growing the array.

NSMutableArray setObject atIndexedSubscript example.

@interface NSMutableArray (NegativeOne)
+(void)load;
-(void)swizzled_setObject:(id)obj atIndexedSubscript:(NSUInteger)idx;
@end

@implementation NSMutableArray (NegativeOne)

+(void)load
{
    Method original = class_getInstanceMethod(self, @selector(setObject:atIndexedSubscript:));
    Method swizzled = class_getInstanceMethod(self, @selector(swizzled_setObject:atIndexedSubscript:));
    method_exchangeImplementations(original, swizzled);
}

-(void)swizzled_setObject:(id)obj atIndexedSubscript:(NSUInteger)idx
{
    if (idx == -1)  idx = [self count];
    [self swizzled_setObject:obj atIndexedSubscript:idx];  // go use the old method: not a typo!
}

@end

Example of [NSMutableArray setObject atIndexedSubscript].
 - (void) setObject:(id)obj atIndexedSubscript:(NSUInteger)index{
    if (index < self.count){
        if (obj)
            [self replaceObjectAtIndex:index withObject:obj];
        else
            [self removeObjectAtIndex:index];
    } else {
        [self addObject:obj];
    }
}

End of NSMutableArray setObject atIndexedSubscript example article.