Declare an ObjC parameter that's a Class conforming to a protocol

前端 未结 2 1504
-上瘾入骨i
-上瘾入骨i 2020-12-30 23:14

In Objective-C, it is possible to pass a class as a parameter to a method:

- (void) methodThatTakesClass:(Class)theClass;

And it is possibl

相关标签:
2条回答
  • 2020-12-30 23:53

    also valid:

    @interface Something: Object {
    }
     - (void) foo:(int(*)(void))bar;
    @end
    
    @implementation Something
    - (void) foo:(int(*)(void))bar {
       return (*bar)();
    }
    @end
    
    int someFunc( void ) {
        return 9;
    }
    
    int main ( int argc, char **argv ) {
        Something *object = [[Something alloc] init];
    
        printf( "%i\n", [object foo:&someFunc] );
    
        [object release];
    
        return 0; 
    }
    
    0 讨论(0)
  • 2020-12-31 00:06

    Yes. The following is a valid program which will log the NSObject class.

    #import <Foundation/Foundation.h>
    void f(Class <NSObject> c) {
        NSLog(@"%@",c);
    }
    int main() {
        f([NSObject class]);
    }
    

    This would cause a compiler error if you tried to pass a class which doesn't conform to NSObject, such as the Object class. You can also use it for methods.

    - (void)printClass:(Class <NSObject>)c;
    
    0 讨论(0)
提交回复
热议问题