检查AppDelegate中是否存在方法/属性



我试图找出AppDelegate是否包含某个属性/方法。为此,我找到了检查类中是否存在属性以及如何检查对象是否具有特定的方法/属性?,但CCD_ 2似乎不同。

以下内容不会编译

if(AppDelegate.HasMethod("SomeMethod"))

因为

AppDelegate不包含HasMethod的定义。

我也尝试了其他变体,但我没有成功地检查方法/属性是否存在。此外,respondsToSelector在这里似乎不适用。GetType()对于AppDelegate也不可用。

检查AppDelegate中是否存在属性/方法的正确方法是什么?

编辑:

我似乎需要一个AppDelegate的实例来处理它。我的问题是如何确保这个实例可用?例如,如果未实现,则通过抛出异常?

以下是您可以做的:

AppDelegate

public static new AppDelegate Self { get; private set; }
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
    AppDelegate.Self = this;
    return true;
}
[Export ("YourMethod:")]
public void YourMethod (bool setVisible){
    // do something
}

某些类别

if(AppDelegate.Self.RespondsToSelector(new Selector("YourMethod:")))
{
    AppDelegate.Self.YourMethod (true);
}

您不需要使用respondsToSelector,如果您有AppDelegate的实例,您也可以使用其他C#/.NET方法(来自链接线程的HasMethodHasProperty)。我的问题是,我如何确保SelfAppDelegate中实现?

是的,编译器会帮我检查,但我只想在方法实现的情况下执行它。它不应该是实现它的必要条件。它也应该在没有YourMethod的情况下工作。

最后我找到了一个解决方案。首先你需要两种扩展方法:

public static class GeneralExtensions
{
    public static bool HasProperty(this object obj, string propertyName)
    {
        return obj.GetType().GetProperty(propertyName) != null;
    }
    public static bool HasMethod(this object objectToCheck, string methodName)
    {
        var type = objectToCheck.GetType();
        return type.GetMethod(methodName) != null;
    } 
}

要检查使用的方法

if (UIApplication.SharedApplication.Delegate.HasMethod("YourMethod")){
    // do something
}

要检查房产,请使用

if (UIApplication.SharedApplication.Delegate.HasProperty("Instance"))
    // do something
}

这个想法来自于这个线索。

但这并不是故事的结束。我的最后一个方法可以在这里找到。

更新答案

我知道这仍然是Obj-C,但你应该能够很容易地获得C#等价物。

#import "AppDelegate.h"
SEL selector = NSSelectorFromString(@"possibleMethod");
AppDelegate * appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
if([appDelegate respondsToSelector:selector]){
    [appDelegate selector];
}

祝好运


首先,

#import "AppDelegate.h"

您可以使用@try块尝试以下方法来测试选择器。

    BOOL methodExists = YES;
    SEL yourVariable = NSSelectorFromString(@"possibleMethod");
    AppDelegate * ad = [[AppDelegate alloc]init];
    @try {
        [ad performSelector:yourVariable withObject:nil afterDelay:0.0];
    }
    @catch (NSException *exception) {
        methodExists = NO;
    }
    @finally {
        if (methodExists) {
            //Call method from selector
        }
    }

最新更新