代码之家  ›  专栏  ›  技术社区  ›  Adam

如何在ObjectiveC类中存储函数指针?

  •  2
  • Adam  · 技术社区  · 14 年前

    一些苹果的 目标-c API仍然使用C函数,例如:

    -(NSArray*)sortedarrayingfunction:(NSInteger(*)(id,id,void*))比较器 上下文:(void*)上下文

    …这很好,除了我正在努力看如何在ObjC类中存储fn指针。

    我相信这很简单,但要么我的C太生锈了,要么就是有问题。我试着在头文件中插入一个普通变量:

    NSInteger(*)(id,id,void*)m压缩机;

    需要标识符或“(”before“)”标记

    4 回复  |  直到 14 年前
        1
  •  1
  •   Dave DeLong    14 年前

    而不是:

    NSInteger (*)(id, id, void *) myComparator;
    

    改用这个:

    NSInteger (* myComparator)(id, id, void *);
    

    (这就像块语法,除了块使用 ^ * )

        2
  •  1
  •   Sam Dufel    14 年前

    真的有必要存储指针吗?为什么不在函数声明中包含.h,然后传入对函数的引用?

        3
  •  1
  •   Laurent Etiemble    14 年前

    可以将函数指针定义为 typedef )然后在类定义中使用它。例如

    在公共标题中:

    typedef NSInteger (*COMPARATOR)(id, id, void *);
    

    @interface MyClass : NSObject {
        NSObject *anotherField;
        COMPARATOR thecomparator;
    }
    
    - (COMPARATOR)comparator;
    
    - (void)setComparator:(COMPARATOR) cmp;
    
    @end
    

    在第二节课上:

    @interface MyOtherClass : NSObject {
        NSObject *afield;
        COMPARATOR thecomparator;
    }
    
    - (COMPARATOR)comparator;
    
    - (void)setComparator:(COMPARATOR) cmp;
    
    @end
    

    类型 COMPARATOR

    编辑:我添加了一些方法来演示如何传递和检索函数指针。

        4
  •  0
  •   benzado    14 年前

    如果要为这样的方法传递函数指针:

    - (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context;
    

    NSInteger myComparisonFunction(id left, id right, void *context) {
        // do stuff...
    }
    

    像这样的typedef:

    typedef NSInteger (ComparisonFunc *)(id, id, void *);
    

    然后在类中,可以声明如下实例变量:

    ComparisonFunc compFunc;
    

    @property (nonatomic) ComparisonFunc compFunc;
    

    然后要设置可以调用的属性:

    myObject.compFunc = myComparisonFunction;
    

    在myObject中,您可以这样使用它:

    sortedArray = [array sortedArrayUsingFunction:compFunc context:NULL];