委托方法无法回调

时间:2015-02-02 08:46:53

标签: ios objective-c callback delegates notifications

委托方法无法回调

这是我的.h文件

@protocol ServiceAPIDelegate <NSObject>
@optional
- (void) onRequestLoginFinish:(NSDictionary*) dict;
@end


@interface ServiceAPI : NSObject
+ (id)shareAPI;
@property (nonatomic, weak) id <ServiceAPIDelegate> delegate_service;
;
@end

这是.m文件,我使用ASIFORMData请求,并在从服务器获得响应后回调到requestFinished。但是,我想将数据发送到myviewcontroler使用[self.delegate_service onRequestLoginFinish:result];在这一行之后。我的程序运行正常而不是错误,而不是回调功能。我看不出错误在哪里。

 - (void) requestLoginWithUserName:(NSString*) username andPassWord:(NSString*) password {
        NSString* urlString = [PublicInstance API_LOGIN];
        NSArray *keys = PARAMS_ARRAY;
        NSArray *objects = [NSArray arrayWithObjects:username, password, [@((int)En) stringValue], APPID, [PublicInstance getDevideID], DEVIDEOS, nil];
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjects:objects forKeys:keys];
        NSString* signData = [PublicInstance signData:dict];
        [dict setObject:signData forKey:signKey];

        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlString]];
        [request addRequestHeader:@"Content-Type" value:@"application/json"];
        [request setValidatesSecureCertificate:NO];
        [request setRequestMethod:@"POST"];

        NSData *jsonDataToPost = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];

        [request appendPostData:jsonDataToPost];

        [request startAsynchronous];
        [request setDelegate:self];
    }

    - (void)requestFinished:(ASIHTTPRequest *)request
    {
        NSError* error = [request error];
        if(!error) {
            NSString* responseString = [request responseString];
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData;
[self.delegate_service onRequestLoginFinish:result];
}else{
            NSLog(@"%@", [error description]);

        }
    }

ServiceAPI *ShareServiceAPI;

- (id) init {
    if ([self init]) {
        ShareServiceAPI = [ServiceAPI shareAPI];
        ShareServiceAPI.delegate_service =self;
    }
}

- (void) requestLoginWithUserInfor:(UserInfor*) _userinfor {
    [ShareServiceAPI requestLoginWithUserName:_userinfor.username andPassWord:_userinfor.password];
}

##################### 这是委托方法 - 但绝不回调(O ^ -oO)

- (void) onRequestLoginFinish:(NSDictionary *)dict {
    if ([[dict objectForKey:Key_Status] intValue] == 1) {
        NSLog(@"login successful");
    }
    else {
        NSLog(@"login fail....");
    }
}

有人可以帮帮我吗?谢谢你的时间

1 个答案:

答案 0 :(得分:0)

您应该始终检查委托是否为nil,并检查委托是否响应选择器:

if(self.delegate_service){
  if([self.delegate_service repondsToSelector:@selector(onRequestLoginFinish:)]){
      [self.delegate_service onRequestLoginFinish:result];
  }
}

通过这种方式,您可以使程序安全,并找到未调用该方法的原因。