【问题标题】:runtime - What does this "@@:" mean in class_addMethod?运行时 - 这个“@@:”在 class_addMethod 中是什么意思?
【发布时间】:2017-09-15 11:08:35
【问题描述】:

使用class_addMethod代码:

class_addMethod(newClass, @selector(inputAccessoryView), accessoryImp, "@@:");

这个方法中参数“@@:”是什么意思?

文档:

/** 
 * Adds a new method to a class with a given name and implementation.
 * 
 * @param cls The class to which to add a method.
 * @param name A selector that specifies the name of the method being added.
 * @param imp A function which is the implementation of the new method. The function must take at least two arguments—self and _cmd.
 * @param types An array of characters that describe the types of the arguments to the method. 
 * 
 * @return YES if the method was added successfully, otherwise NO 
 *  (for example, the class already contains a method implementation with that name).
 *
 * @note class_addMethod will add an override of a superclass's implementation, 
 *  but will not replace an existing implementation in this class. 
 *  To change an existing implementation, use method_setImplementation.
 */
OBJC_EXPORT BOOL class_addMethod(Class cls, SEL name, IMP imp, 
                             const char *types) 
OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0);

【问题讨论】:

    标签: ios objective-c runtime


    【解决方案1】:

    您知道 Objective 中的方法具有以下签名

    (返回类型)(function_name)(id self, SEL cmd, ...)

    @@: 意思 代表返回类型的第一个字符。 @mean 对象类型(类类型) 第二个self参数 第三个是SEL 该函数没有参数,因此以:结尾

    例如: "v@:i@"

    -(void)functionName:(int)arg arg2:(id)arg2;
    

    意思

    1. v: 是返回类型为 void 类型 @: 是自我和SEL i 是一个整数参数 @ 是一个对象类型参数

    您可以查看 Apple 文档以进一步了解。 https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html#//apple_ref/doc/uid/TP40008048-CH100

    【讨论】:

      【解决方案2】:

      types 参数描述了参数和返回类型 方法如中所述 class_addMethod:

      描述方法参数类型的字符数组。有关可能的值,请参阅Objective-C Runtime Programming Guide > Type Encodings。由于函数必须至少有两个参数——self_cmd,所以第二个和第三个字符必须是“@:”(第一个字符是返回类型)。

      "@@:" 描述了一个返回对象的方法 (类型编码@,在您的情况下为:UIView *),除了固定(隐藏)参数self(对象类型编码@)和_cmd(类型编码:选择器)。

      【讨论】:

      • 如果 SEL@selector(viewWithObject:) ,那么 types 将是 "@@:@" ?
      • @tom:如果该方法将对象作为参数并返回一个对象,则为是。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-07
      • 2010-12-30
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      • 2011-04-11
      相关资源
      最近更新 更多