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?
#import <UIKit/UIKit.h>
#import "CustomObject.h"
@interface UIViewController ()
@property (nonatomic, strong) CustomObject *customObject;
@end
#import <UIKit/UIKit.h>
#import "UIViewController_CustomObject.h"
@interface UIViewController (CustomObject)
- (void)customMethod;
@end
#import "UIViewController+CustomObject.h"
@implementation UIViewController (CustomObject)
- (void)customMethod
{
[self.customObject doSomething];
}
@end
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With