Search code examples
iosobjective-cobjective-c-category

How can I access the object on which a category method was called?


I'm using @implementation to add a new function to UIView.

@implementation UIView (test)
    - (void)newFunction {

    }
@end

Now, in the newFunction I want to "grab" the object (UIView) that was used when calling the function.

For example when I call newFunction within viewDidLoad

- (void)viewDidLoad {
    [myView newFunction];
}

I want the newFunction to know what object was used to make the call (in this case, myView).

A simple solution would be to pass it along when making the call ([myView newFunction:myView]), but that is not what I am looking for.

I looked at Apple's documentation on the subject, but didn't really find an answer to my question.


Solution

  • What you describe is called a category (not @implementation). It is an extension to the UIView class (in this case).

    Generalcally:

    @implementation __CLASS_TO_EXTEND__ (__CATEGORY_NAME__)
    

    The category, as it is an extension, is the instance that you call the method on. So, you use self as you usually would to access the current instance.