如何在Objective-C中實作鍊式語法?
例如:
someObject.a.and.b.someMethod(5)
這裡主要指的是點鍊式語法,不同於常見的[[[[someObject a] and] b] someMethod:5]
中括號鍊式語法。
如何設計?
天蓬老师2017-04-24 09:13:13
透過Stackoverflow已經解決了這個問題。連結網址:http://stackoverflow.com/questions/27739106/how-to-implement-chainable-syntax-with-objective-c/27740550#27740550
範例:
@class ClassB;
@interface ClassA : NSObject
//1. we define some the block properties
@property(nonatomic, readonly) ClassA *(^aaa)(BOOL enable);
@property(nonatomic, readonly) ClassA *(^bbb)(NSString* str);
@property(nonatomic, readonly) ClassB *(^ccc)(NSString* str);
@implement ClassA
//2. we implement these blocks, and remember the type of return value, it's important to chain next block
- (ClassA *(^)(BOOL))aaa
{
return ^(BOOL enable) {
//code
if (enable) {
NSLog(@"ClassA yes");
} else {
NSLog(@"ClassA no");
}
return self;
}
}
- (ClassA *(^)(NSString *))bbb
{
return ^(NSString *str)) {
//code
NSLog(@"%@", str);
return self;
}
}
// Here returns a instance which is kind of ClassB, then we can chain ClassB's block.
// See below .ccc(@"Objective-C").ddd(NO)
- (ClassB * (^)(NSString *))ccc
{
return ^(NSString *str) {
//code
NSLog(@"%@", str);
ClassB* b = [[ClassB alloc] initWithString:ccc];
return b;
}
}
//------------------------------------------
@interface ClassB : NSObject
@property(nonatomic, readonly) ClassB *(^ddd)(BOOL enable);
- (id)initWithString:(NSString *)str;
@implement ClassB
- (ClassB *(^)(BOOL))ddd
{
return ^(BOOL enable) {
//code
if (enable) {
NSLog(@"ClassB yes");
} else {
NSLog(@"ClassB no");
}
return self;
}
}
// At last, we can do it like this------------------------------------------
id a = [ClassA new];
a.aaa(YES).bbb(@"HelloWorld!").ccc(@"Objective-C").ddd(NO)
有更好的看法或想法,討論繼續 :]