Question

I have a class (SomeClass) that I am extending and adding a property (propOne) to. I also want to add a category (CategoryName) on this class to create a method that modifies the property added in the extension.

I'm getting a compiler error message saying [SomeClass setPropOne:] unrecognized selector...

I'm pretty new to objective-c - how can a method created in a category modify a property added via an extension?

I think what I'm trying to do can be best explained with code:

@interface SomeClass ()

@property (nonatomic,weak) id propOne

@end

...
...


@implementation SomeClass (CategoryName)

- (void)someMethodWithParam:(id)param
{
 self.propOne = param;
}

@end
Was it helpful?

Solution

It is not possible to add an @property to a category out of the box. However there is a workaround that involves creating something like this:

static const char kMyChar;

And binding it to the category (making it an "associated object") via something like this:

objc_setAssociatedObject(self, &kMyChar, alertWrapper, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

Take a look here for complete documentation of a good example that "adds a property" to a block-based UIAlertView category...

OTHER TIPS

The auto-synthesis mechanism can synthesize a property declared in a class extension only if the class extension is visible when the implementation is compiled. So if the class extension shown in your example was either in SomeClass.h or SomeClass.m, the property would be synthesized.

Otherwise, the class extension is providing a declaration for a (in this case at least) non-existent property, which is why you're seeing a runtime exception when you try to access it. To fix that, you could implement the accessor methods yourself in the SomeClass (CategoryName) category.

The problem you may be facing then is that is that there's no way for a given class to add an instance variable to another class. See Alfie Hansen's answer for a possible workaround for that.

Implementation to do what you want by using associated object.
https://github.com/kissrobber/DProperty

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top