从 Method 到 SEL 的类型转换

发布于 2024-12-14 13:30:42 字数 103 浏览 5 评论 0原文

我正在使用 Objective-C 运行时库函数 class_copyMethodList() 来获取类中所有方法的列表。然后如何将这些 Method 类型对象转换为可用的 SEL 类型对象?

I’m using the Objective-C runtime library, function class_copyMethodList(), to get a list of all the methods in my class. How do I then convert those type Method objects into usable type SEL objects?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

木格 2024-12-21 13:30:42

对返回的 Method 对象运行函数 method_getName()

Run the function method_getName() on the returned Method objects.

橪书 2024-12-21 13:30:42

几年前我这样做是为了提取类方法的所有名称。您可以使用 NSSelectorFromString() 从每个名称中获取 SEL。

+ (NSArray *) methodNamesForClass:(Class) aClass
{
    Method *methods;
    unsigned int methodCount;
    if (methods = class_copyMethodList(aClass, &methodCount))
    {
        NSMutableArray *results = [NSMutableArray arrayWithCapacity:methodCount];
        while (methodCount--) 
            [results addObject:[NSString stringWithCString: sel_getName(method_getName(methods[methodCount])) 
                                                  encoding: NSASCIIStringEncoding]];
        free(methods);  
        return results;
    }

    return nil;
}

I did this a couple of years back to extract all the names of a class's methods. You could use NSSelectorFromString() to get the SEL from each name.

+ (NSArray *) methodNamesForClass:(Class) aClass
{
    Method *methods;
    unsigned int methodCount;
    if (methods = class_copyMethodList(aClass, &methodCount))
    {
        NSMutableArray *results = [NSMutableArray arrayWithCapacity:methodCount];
        while (methodCount--) 
            [results addObject:[NSString stringWithCString: sel_getName(method_getName(methods[methodCount])) 
                                                  encoding: NSASCIIStringEncoding]];
        free(methods);  
        return results;
    }

    return nil;
}
青柠芒果 2024-12-21 13:30:42

假设您知道方法的名称,您可以使用 NSSelectorFromString 函数将其转换为选择器。

SEL fooSelector = NSSelectorFromString ( @"foo:" ) ; 

Apple 在他们的 Objective C 教程。

Assuming you have the name of the method, you can convert it to a selector using the NSSelectorFromString function.

SEL fooSelector = NSSelectorFromString ( @"foo:" ) ; 

Apple discusses this in their Objective C tutorial.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文