Does Objective-C support Mixin like Ruby?

后端 未结 4 1887
一向
一向 2020-12-24 12:53

In Ruby, there\'s Modules and you can extend a class by \"mixing-in\" the module.

module MyModule
  def printone
    print \"one\" 
  end
end

class MyClass
         


        
4条回答
  •  孤城傲影
    2020-12-24 13:27

    You can literally mixin the code using #include. This is not advisable and is against all the religions in objective-c, however works perfectly.

    Please, don't do it in the production code.

    for example in the file:

    MixinModule.header (should not be compiled or copied to the target)

    -(void)hello;
    

    MixinModule.body (should not be compiled or copied to the target)

    -(void)hello{
        NSLog(@"Hello");
    }
    

    in mixin class:

    @interface MixinTest : NSObject
    #include "MixinModule.header"
    @end
    
    @implementation MixinTest
    #include "MixinModule.body"
    @end
    

    usage case:

    #import 
    
    int main(int argc, const char * argv[]){
        @autoreleasepool {
            [[[MixinTest new] autorelease] hello];
        }
        return 0;
    }
    

    Please, don't do it in the production code.

提交回复
热议问题