如何在Objective-C中实现链式语法?

 白斌童鞋 发布于 2022-10-25 02:46

如何在Objective-C中实现链式语法?

例如:

someObject.a.and.b.someMethod(5)

这里主要指的是点链式语法,不同于常见的[[[[someObject a] and] b] someMethod:5] 中括号链式语法

如何设计?

1 个回答
  • 通过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)
    

    有更好的看法或者想法,讨论继续 :]

    2022-10-26 14:07 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有