AHKBuilder allows you to add initialization based on the builder pattern to your immutable objects with ease. Implementation is described in the blog post: http://holko.pl/2015/05/12/immutable-object-initialization/
Let's say you have a simple Reminder class:
@interface Reminder : NSObject
@property (nonatomic, copy, readonly) NSString *title;
@property (nonatomic, strong, readonly) NSDate *date;
@property (nonatomic, assign, readonly) BOOL showsAlert;
@endWith just three simple steps you can add ability to your classes to be initialized with the builder block:
-
Import
AHKBuilderwith#import <AHKBuilder/AHKBuilder.h> -
Add a protocol declaring same properties as your immutable class, but with
readwritemodifier, in our case:
@protocol ReminderBuilder <NSObject>
@property (nonatomic, copy, readwrite) NSString *title;
@property (nonatomic, strong, readwrite) NSDate *date;
@property (nonatomic, assign, readwrite) BOOL showsAlert;
@end- Declare initialization and/or copying method using the name of protocol from 1.
@interface Reminder (Builder)
- (instancetype)initWithBuilder_ahk:(void (^)(id<ReminderBuilder> builder))builderBlock;
- (instancetype)copyWithBuilder_ahk:(void (^)(id<ReminderBuilder> builder))builderBlock;
@endNote: These methods have to be declared in a category, otherwise Xcode will complain that their definitions are missing.
That's all! You can now create instances and copies using these methods, e.g.:
Reminder *reminder = [[Reminder alloc] initWithBuilder_ahk:^(id<ReminderBuilder> builder) {
builder.title = @"Test reminder";
}];- iOS 8 and above
Source files can be found in AHKBuilder folder. AHKBuilder is compatible with Carthage.
Fixed crash when working with objects conforming to protocols inheriting from NSObject.
Initial release.
Arkadiusz Holko: