Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-synthesis of properties of variables in a class extension

I need to add one instance variable and two methods that use that instance variable to UIViewController. I added a property for the variable in a class extension. I then made a category for UIViewController that had the method names. The category header file imports the class extension.

To use the category, I import it in my own custom view controllers. However, when I call one of the category methods (that makes use of the property declared in the extension), it crashes.

I can get around this by synthesizing the property in my subclass of UIViewController, but I thought that these should be synthesized automatically.

Am I missing something?

UIViewController_CustomObject.h (Extension Header)

 #import <UIKit/UIKit.h>
 #import "CustomObject.h"

 @interface UIViewController ()

 @property (nonatomic, strong) CustomObject *customObject;

 @end

UIViewController+CustomObject.h (Category Header)

 #import <UIKit/UIKit.h>
 #import "UIViewController_CustomObject.h"

 @interface UIViewController (CustomObject)

 - (void)customMethod;

@end

UIViewController+CustomObject.m (Category Implementation)

 #import "UIViewController+CustomObject.h"

 @implementation UIViewController (CustomObject)

 - (void)customMethod
 {
      [self.customObject doSomething];
 }

@end

like image 930
Ross Kimes Avatar asked Nov 13 '22 17:11

Ross Kimes


1 Answers

I would recommend using only a category and associated objects instead.

UIViewController+CustomObject.h

#import <UIKit/UIKit.h>
#import "CustomObject.h"

@interface UIViewController (CustomObject)
@property (nonatomic, strong) CustomObject *customObject;

- (void)customMethod;

@end

UIViewController+CustomObject.m

#import <objc/runtime.h>
#import "UIViewController+CustomObject.h"

static char customObjectKey;

@implementation UIViewController (CustomObject)

- (CustomObject *)customObject{
    CustomObject *_customObject= objc_getAssociatedObject(self, &customObjectKey);
    return _taskDateBarView;
}

- (void)setCustomObject :(CustomObject *)_customObject{
    objc_setAssociatedObject(self, &customObjectKey, _customObject, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)customMethod
{
     [self.customObject doSomething];
}

@end
like image 190
patric.schenke Avatar answered Nov 15 '22 08:11

patric.schenke