There are more ways on how to approach this - depending on what exactly you would like to achieve.
If this methods are tied with UIViewController
's life and data you would probably want to subclass UIViewController
or make an UIViewController
category.
A: Subclassing (you want to add some custom properties, variables, methods or you want to override a method):
MySubclassedViewController.h
#import <UIKit/UIKit.h>
@interface MySubclassedViewController : UIViewController
@property (copy) NSString *myVerySpecialString;
-(void) myVerySpecialMethod;
@end
MySubclassedViewController.m
#import "MySubclassedViewController.h"
@implementation MySubclassedViewController
-(void) initialization
{
self.myVerySpecialString = @"initialized";
}
- (id)initWithCoder:(NSCoder*)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
[self initialization];
}
return self;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
[self initialization];
}
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
[self initialization];
}
return self;
}
-(void) viewDidLoad
{
[super viewDidLoad];
[self myVerySpecialMethod];
}
-(void) myVerySpecialMethod
{
if ([self.myVerySpecialString isEqualToString: @"initialized"])
{
self.backgroundColor = [UIColor yellowColor];
}
}
@end
B: Category (you just want to add some extra method to a class):
UIViewController+SpecialCatrgory.h
#import <UIKit/UIKit.h>
@interface UIViewController (SpecialCategory)
-(void) myVerySpecialMethod;
@end
UIViewController+SpecialCatrgory.m
#import "UIViewController+SpecialCatrgory.h"
@implementation UIViewController (SpecialCategory)
-(void) myVerySpecialMethod
{
self.backgroundColor = [UIColor yellowColor];
}
@end
C: Dedicated helper class
On the other hand if you find yourself using some independent method on more than one place you might want to consider writing up a helper class and use it as a singleton.
MyHelperClass.h
@interface MyHelperClass : NSObject
+ (instancetype)sharedHelper;
-(NSString *) myVerySpecialMethod;
@end
MyHelperClass.m
#import "MyHelperClass.h"
@implementation MyHelperClass
+ (instancetype)sharedHelper
{
static MyHelperClass *_sharedHelper = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedHelper = [[MAConnectionClient alloc] init];
});
return _sharedHelper;
}
-(NSString *) myVerySpecialMethod
{
return @"a result from your very special method";
}
@end
You use it simply by importing MyHelperClass.h
(or putting it in -Prefix.pch
), without explicitly creating an instance. For example:
NSString *someString = [[MyHelperClass sharedHelper] myVerySpecialMethod];