我正在尝试在 iOS 中实现我自己的 API,但我在回调方面遇到一个问题。
我已经使用选择器实现了回调,但是,当给定的函数位于另一个文件/类中时,应用程序崩溃。
这是错误:
2013-09-18 21:32:16.278 Vuqio[6498:19703] -[VuqioApi postCurrenProgramRequestDidEnd]: unrecognized selector sent to instance 0xa5a2150
2013-09-18 21:32:16.278 Vuqio[6498:19703] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[VuqioApi postCurrenProgramRequestDidEnd]: unrecognized selector sent to instance 0xa5a2150'
这是我的代码:
调用:(文件Controller.m)
...
[self softCheckIn:@"922337065874264868506e30fda-1c2a-40a5-944e-1a2a13e95e95" inProgram:p.idProgram callback:@selector(postCurrenProgramRequestDidEnd)];
...
-(void)postCurrenProgramRequestDidEnd
{
NSLog(@"Soft check-in");
}
- (void)softCheckIn:(NSString *)userId inProgram:(NSString *)program callback:(SEL)callback
{
// Hacemos un soft checkin
VuqioApi *api = [[VuqioApi alloc] init];
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
userId, @"userId",
program, @"programId",
nil];
[api postCurrentProgram:data withSuccess:callback andFailure:@selector(aaa)];
}
方法:(文件Api.m)
- (void)postCurrentProgram:(NSDictionary *)data withSuccess:(SEL)successCallback
{
NSLog(@"Performing selector: %@", NSStringFromSelector(successCallback));
[self postCurrentProgram:data withSuccess:successCallback andFailure:@selector(defaultFailureCallback)];
}
- (void) postCurrentProgram:(NSDictionary *)data withSuccess:(SEL)successCallback andFailure:(SEL)failureCallback {
[self placePostRequest:@"api/programcurrent" withData:data withHandler:^(NSURLResponse *urlResponse, NSData *rawData, NSError *error) {
NSLog(@"Performing selector: %@", NSStringFromSelector(successCallback));
NSLog(@"Performing selector: %@", NSStringFromSelector(failureCallback));
NSString *string = [[NSString alloc] initWithData:rawData encoding:NSUTF8StringEncoding];
//NSDictionary *json = [NSJSONSerialization JSONObjectWithData:rawData options:0 error:nil];
if ( ![string isEqual: @"ok"])
{
[self performSelector:failureCallback withObject:self];
} else {
NSLog(@"OK");
[self performSelector:successCallback];
}
}];
}
- (void) defaultFailureCallback {
NSLog(@"Failure");
}
选择器是在某种类型的实例上执行的。您需要传递将向其发送选择器消息的对象以及选择器。
在上面的例子中,您在 Controller.m
aaa
中有一个选择器,这可能是 Controller
实例上的有效方法,但在 Api.m 文件中,您尝试调用该方法 aaa
在 Api
的实例上,这会导致崩溃,因为该方法对该类无效。