Skip to content

Instantly share code, notes, and snippets.

@ratkins
Last active April 6, 2017 20:22
Show Gist options
  • Save ratkins/1e4a62558754377fc0e5 to your computer and use it in GitHub Desktop.
Save ratkins/1e4a62558754377fc0e5 to your computer and use it in GitHub Desktop.
Avoid polluting an Objective-C implementation with builder-related code by "hiding" it in a category
#import "GroupableItem.h"
@interface GroupableItemBuilder : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *groupingKey;
@property (nonatomic, assign) NSInteger second;
@property (nonatomic, assign) NSInteger minute;
@property (nonatomic, assign) NSInteger hour;
@property (nonatomic, assign) NSInteger day;
@property (nonatomic, assign) NSInteger month;
@property (nonatomic, assign) NSInteger year;
@end
@interface GroupableItem (Builder)
+ (GroupableItem *)itemWithBlock:(void (^)(GroupableItemBuilder *builder))block;
@end
#import "GroupableItem+Builder.h"
@implementation GroupableItemBuilder
- (instancetype)init
{
self = [super init];
if (self) {
_name = @"Default Name";
_groupingKey = @"Default Grouping Property Value";
_second = 0;
_minute = 0;
_hour = 6;
_day = 25;
_month = 4;
_year = 1915;
}
return self;
}
@end
@implementation GroupableItem (Builder)
+ (GroupableItem *)itemWithBlock:(void (^)(GroupableItemBuilder *))block
{
GroupableItemBuilder *builder = [[GroupableItemBuilder alloc] init];
block(builder);
GroupableItem *item = [[GroupableItem alloc] init];
item.name = builder.name;
item.groupingKey = builder.groupingKey;
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.second = builder.second;
dateComponents.minute = builder.minute;
dateComponents.hour = builder.hour;
dateComponents.day = builder.day;
dateComponents.month = builder.month;
dateComponents.year = builder.year;
item.date = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] dateFromComponents:dateComponents];
return item;
}
@end
#import <Foundation/Foundation.h>
@interface GroupableItem : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *groupingKey;
@property (nonatomic, strong) NSDate *date;
@end
#import "GroupableItem.h"
@implementation GroupableItem
@end
- (void)setUp
{
[super setUp];
//...
self.items = @[
[GroupableItem itemWithBlock:^(GroupableItemBuilder *builder) {
builder.name = @"0";
builder.hour = 9;
builder.minute = 30;
}],
[GroupableItem itemWithBlock:^(GroupableItemBuilder *builder) {
builder.name = @"1";
builder.hour = 9;
builder.minute = 30;
builder.second = 1;
}],
[GroupableItem itemWithBlock:^(GroupableItemBuilder *builder) {
builder.name = @"2";
builder.hour = 10;
builder.minute = 0;
}],
//...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment