运行时 - class_addMethod 中的 "@@:" 是什么意思?

4
使用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);
2个回答

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

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

"@@:" 表示一个方法返回一个对象(类型编码 @,在您的情况下为:UIView *)并且除了固定(隐藏)参数 self(类型编码为 @ 的对象)和 _cmd(类型编码为 : 的选择器)外没有其他参数。


如果 SEL@selector(viewWithObject:),那么 types 将会是 "@@:@" 吗? - tomfriwel
@tom:如果该方法以对象作为参数并返回一个对象,则是的。 - Martin R

1

你知道Objective中的方法有以下签名:

(返回类型)(函数名)(id self, SEL cmd, ...)

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

例如:"v@:i@"

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

mean

  1. v:返回void类型 @:代表self和SEL i:整数类型参数 @:对象类型参数

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接