Search code examples
objective-cmethods

How to access an array calling a category method within the method itself?


I am new to Objective-C. I'm trying to create a category method for arrays that doesn't use a parameter. I'm told there is a way that the method can use this array without using the array as an argument. I haven't seen much specific to this question. Can anyone tell me how to access the array calling the method from within the category method?

I know using an argument works. Like this:

[array reversed:array];

I'm trying to do this instead:

[array reversed];

Solution

  • In your example, array is not calling anything. It is the object that the reversed message is passed to. Within the -reversed method, the object being passed the method (array in this case) is called self, which is how you would access it in a category, or any method of an object.

    In your example, that would look something like:

    @interface NSArray (Reversed)
    - (NSArray *)reversed;
    @end
    
    @implementation NSArray (Reversed)
    
    - (NSArray *)reversed {
        NSMutableArray *result = [NSMutableArray new];
    
        // Here is where you refer to the target as `self`
        for (id element in [self reverseObjectEnumerator]) {
            [result addObject: element];
        }
        return result;
    }
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            NSArray *xs = @[@1, @2, @3];
            NSArray *reversed = [xs reversed];
            NSLog(@"%@ -> %@", xs, reversed);
        }
        return 0;
    }