A lightweight dependency injection framework for Objective-C. With support for iOS and MacOS X.
A class can be registered with objection using the macros objection_register or objection_register_singleton. The objection_requires macro can be used to declare what dependencies objection should provide to all instances it creates of that class. objection_requires can be used safely with inheritance.
@class Engine, Brakes;
@interface Car : NSObject
{
Engine *engine;
Brakes *brakes;
BOOL awake;
}
// Will be filled in by objection
@property(nonatomic, retain) Engine *engine;
// Will be filled in by objection
@property(nonatomic, retain) Brakes *brakes;
@property(nonatomic) BOOL awake;
@implementation Car
objection_register(Car)
objection_requires(@"engine", @"brakes")
@synthesize engine, brakes, awake;
@end
An object can be fetched from objection by creating an injector and then asking for an instance of particular class. An injector manages its own object context. Which means that a singleton is per injector and is not necessarily a true singleton.
- (void)someMethod {
ObjectionInjector *injector = [Objection createInjector];
id car = [injector getObject:[Car class]];
}
A global injector can registered with Objection which can be used throughout your application or library.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
ObjectionInjector *injector = [Objection createInjector];
[Objection setGlobalInjector:injector];
}
- (void)viewDidLoad {
id myModel = [[Objection globalInjector] getObject:[MyModel class]];
}
Objection supports associating an object outside the context of Objection by configuring an ObjectionModule.
@interface MyAppModule : ObjectionModule {
}
@end
@implementation MyAppModule
- (void)configure {
[self bind:[UIApplication sharedApplication] toClass:[UIApplication class]];
}
@end
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
ObjectionInjector *injector = [Objection createInjector:[[[MyAppModule alloc] init] autorelease]];
[Objection setGlobalInjector:injector];
}
If an object is interested in knowing when it has been fully instantiated by objection it can implement the method awakeFromObjection.
@implementation Car
//...
objection_register_singleton(@"Car")
- (void)awakeFromObjection {
awake = YES;
}
@end
- Diagram class initialization and its relationship with Objection
- Add support for Protocol based dependencies
- git clone git://github.com/atomicobject/objection.git
- Open Objection.xcodeproj
- Select Objection-iPhone target
- Select Release Configuration
- Build
- Add -ObjC and -all_load to Other Link Flags in your project
#import <Objection-iPhone/Objection.h>
- git clone git://github.com/atomicobject/objection.git
- Open Objection.xcodeproj
- Select Objection target
- Select Release Configuration.
- Build
#import <Objection/Objection.h>
- MacOS X 10.6 +
- iOS 3.0 +