gpt4 book ai didi

objective-c - 不能调配类方法

转载 作者:太空狗 更新时间:2023-10-30 03:57:21 25 4
gpt4 key购买 nike

我正在为 Mail.app 制作一个插件。我希望插件在邮件的工具栏中添加一个按钮。为此,我决定最好的方法是调用函数在 MessageViewer 的初始化方法中添加此按钮(MessageViewer 是 Mail.app 的 FirstResponder 的类)。我正在修改的代码似乎运行良好:

+ (void) initialize
{
[super initialize];

// class_setSuperclass([self class], NSClassFromString(@"MVMailBundle"));
// [ArchiveMailBundle registerBundle];


// Add a couple methods to the MessageViewer class.
Class MessageViewer = NSClassFromString(@"MessageViewer");

// swizzleSuccess should be NO if any of the following three calls fail
BOOL swizzleSuccess = YES;
swizzleSuccess &= [[self class] copyMethod:@selector(_specialValidateMenuItem:)
fromClass:[self class]
toClass:MessageViewer];
swizzleSuccess &= [[self class] copyMethod:@selector(unsubscribeSelectedMessages:)
fromClass:[self class]
toClass:MessageViewer];

但是,当我尝试这样做时,它不起作用:

//  //Copy the method to the original MessageViewer
swizzleSuccess &= [[self class] copyMethod:@selector(_specialInitMessageViewer:)
fromClass:[self class]
toClass:MessageViewer];

调配方法如下:

+ (BOOL)swizzleMethod:(SEL)origSel withMethod:(SEL)altSel inClass:(Class)cls
{
// For class (cls), swizzle the original selector with the new selector.
//debug lines to try to figure out why swizzling is failing.
// if (!cls || !origSel) {
// NSLog(@"Something was null. Uh oh.");
//}
Method origMethod = class_getInstanceMethod(cls, origSel);

if (!origMethod) {
NSLog(@"Swizzler -- original method %@ not found for class %@", NSStringFromSelector(origSel),
[cls className]);
return NO;
}
//if (!altSel) NSLog(@"altSel null. :(");
Method altMethod = class_getInstanceMethod(cls, altSel);
if (!altMethod) {
NSLog(@"Swizzler -- alternate method %@ not found for class %@", NSStringFromSelector(altSel),
[cls className]);
return NO;
}

method_exchangeImplementations(origMethod, altMethod);

return YES;

}


+ (BOOL) copyMethod:(SEL)sel fromClass:(Class)fromCls toClass:(Class)toCls
{
// copy a method from one class to another.
Method method = class_getInstanceMethod(fromCls, sel);
if (!method)
{
NSLog(@"copyMethod-- method %@ could not be found in class %@", NSStringFromSelector(sel),
[fromCls className]);
return NO;
}
class_addMethod(toCls, sel,
class_getMethodImplementation(fromCls, sel),
method_getTypeEncoding(method));
return YES;
}

似乎在调用 class_getInstanceMethod 时失败了,因为我在日志中收到错误消息。我自己的类中的方法以及 MessageViewer 的初始化方法都会发生这种情况。

这里有没有我没有考虑到的问题?

最佳答案

如果您想调配类方法,那么为什么要使用 class_getInstanceMethod() 函数而不是 class_getClassMethod()

关于objective-c - 不能调配类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4383567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com