Reputation: 2733
In this project,ArrayDataSource
class has a public method using typedef-ing block as a parameter:
Origin was like:
//ArrayDataSource.h
typedef void (^TableViewCellConfigureBlock)(id cell, id item);
- (id)initWithItems:(NSArray *)anItems
cellIdentifier:(NSString *)aCellIdentifier
configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock;
//ArrayDataSource.m
@property (nonatomic, copy) TableViewCellConfigureBlock configureCellBlock;
- (id)initWithItems:(NSArray *)anItems
cellIdentifier:(NSString *)aCellIdentifier
configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock
{
self = [super init];
if (self) {
self.items = anItems;
self.cellIdentifier = aCellIdentifier;
self.configureCellBlock = [aConfigureCellBlock copy];
}
return self;
}
Why not make it :
//ArrayDataSource.h
//no typedef
- (id)initWithItems:(NSArray *)anItems
cellIdentifier:(NSString *)aCellIdentifier
configureCellBlock:(void(^)(id cell, id item))aConfigureCellBlock;
//ArrayDataSource.m:
@property (nonatomic, copy) void*(^configBlock)(id cell, id item);
- (id)initWithItems:(NSArray *)anItems cellIdentifier:(NSString *)aCellIdentifier configureCellBlock:(void (^)(id, id))aConfigureCellBlock{
self = [super init];
if (self) {
self.items = anItems;
self.cellIdentifier = aCellIdentifier;
self.configBlock = [aConfigureCellBlock copy];
}
return self;
}
Any advantage of doing so?
Upvotes: 0
Views: 282
Reputation: 5326
The block syntax is not the Objective-C style...
Using typedef
make your code nicer.
It also allow you to reuse the same block type in many cases. (If you will think on server request block, and many request methods that each has the same response block as parameter, using the typedef will prevent the reuse of code...)
Upvotes: 1
Reputation: 3701
The whole idea behind typedef
ing blocks is that is makes ObjC look much cleaner and nicer. If you have a block like:
NSMutableAttributedString *(^)(UIFont *, UIColor *, const CGFloat, NSString *)
Which gets taken as a parameter you get a giant mess which is hard to read. If you typedef
it, it becomes much nicer since you only pass the typedef
name around. And it's also a lot simpler to understand if you name it like AttributedStringAssemblerBlock
.
The thing with blocks is that they are fairly new to ObjC and don't have the right look and feel for it. Closures in swift are a lot nicer and have a nicer fit in the language.
The second thing is reuse as pointed out in the comments. Having generic typedefs for blocks makes them reusable all over the place.
Upvotes: 0