将方法作为 SEL 参数传递给另一个类方法

Posted

技术标签:

【中文标题】将方法作为 SEL 参数传递给另一个类方法【英文标题】:Pass method as an SEL argument to another class method 【发布时间】:2011-08-16 17:44:13 【问题描述】:

我有一个 appDelegate,它初始化了一个名为 LocationService 的类的实例。 我只是想通过 init 向这个实例传递一个该类将运行的方法。

我遇到了这个异常:

2011-08-16 20:38:15.233 WalklogAnywhere[8258:307] -[LocationService setBackgroundActionMethod:]: unrecognized selector sent to instance 0x17a740
2011-08-16 20:38:15.249 WalklogAnywhere[8258:307] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[LocationService setBackgroundActionMethod:]: unrecognized selector sent to instance 0x17a740'
*** Call stack at first throw:
(
        0   CoreFoundation        0x314d0987 __exceptionPreprocess + 114
        1   libobjc.A.dylib       0x319a149d objc_exception_throw + 24
        2   CoreFoundation        0x314d2133 -[NSObject(NSObject) doesNotRecognizeSelector:] + 102
        3   CoreFoundation        0x31479aa9 ___forwarding___ + 508
        4   CoreFoundation        0x31479860 _CF_forwarding_prep_0 + 48
        5   WalklogAnywhere       0x00004013 -[LocationService initWithBackgroundMethod:] + 206
        6   WalklogAnywhere       0x0000246b -[WalklogAnywhereAppDelegate application:didFinishLaunchingWithOptions:] + 110
        7   UIKit                 0x338dabc5 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 772
        8   UIKit                 0x338d6259 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 272
        9   UIKit                 0x338a248b -[UIApplication handleEvent:withNewEvent:] + 1114
        10  UIKit                 0x338a1ec9 -[UIApplication sendEvent:] + 44
        11  UIKit                 0x338a1907 _UIApplicationHandleEvent + 5090
        12  GraphicsServices      0x35d66f03 PurpleEventCallback + 666
        13  CoreFoundation        0x314656ff __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 26
        14  CoreFoundation        0x314656c3 __CFRunLoopDoSource1 + 166
        15  CoreFoundation        0x31457f7d __CFRunLoopRun + 520
        16  CoreFoundation        0x31457c87 CFRunLoopRunSpecific + 230
        17  CoreFoundation        0x31457b8f CFRunLoopRunInMode + 58
        18  UIKit                 0x338d5309 -[UIApplication _run] + 380
        19  UIKit                 0x338d2e93 UIApplicationMain + 670
        20  WalklogAnywhere       0x000021bb main + 70
        21  WalklogAnywhere       0x00002170 start + 40
)
terminate called after throwing an instance of 'NSException'

这是我的应用程序委托类方法,它初始化 LocationService 实例:

-(void) backgroundLocationUpdate 
    NSLog(@"location is updated in background");



#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application
     didFinishLaunchingWithOptions:(NSDictionary *)launchOptions     

    // Override point for customization after application launch.

    [self.window makeKeyAndVisible];
    locationService = [[LocationService alloc]
            initWithBackgroundMethod:@selector(backgroundLocationUpdate:)];
    [locationService startForegroundService];
    storageService = [[StorageService alloc] init];
    [self loadApplicationData];

    return YES;

这是 LocationService 类方法:

-(id) initWithBackgroundMethod:(SEL)selector 
    self = [super init];
    if (self != nil) 
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.backgroundActionMethod = selector;
    
    return self;

请帮帮我。 非常感谢!

【问题讨论】:

【参考方案1】:

选择器只是一个方法的名称。它与类无关,也与类的实例无关。

如果你想有一种回调,使用选择器,你必须提供一个目标对象以及选择器。

然后,调用目标对象的选择器,使用继承自 NSObject 的 performSelector 方法。

有关错误检查,请参阅respondToSelector 方法。

【讨论】:

【参考方案2】:

删除 backgroundLocationUpdate 旁边的冒号,如下所示:

[self.window makeKeyAndVisible]; locationService = [[LocationService alloc] initWithBackgroundMethod:@selector(backgroundLocationUpdate)]; 

因为冒号使它寻找带有 (id)sender 参数的方法。

【讨论】:

【参考方案3】:

错误来自这一行:

self.backgroundActionMethod = selector;

我猜你实际上没有 backgroundActionMethod 属性,因为没有 -setBackgroundActionMethod: 方法。

【讨论】:

以上是关于将方法作为 SEL 参数传递给另一个类方法的主要内容,如果未能解决你的问题,请参考以下文章

C#将方法作为参数传递给另一个方法[重复]

对象作为参数传递给另一个类,通过值还是引用?

将一个函数的所有参数传递给另一个函数

当我们将对象作为参数传递给方法时,为啥会调用复制构造函数?

将超类作为参数传递给期望子类的方法

将实例变量作为参数传递给同一类中的方法?