You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Objective-C error回调block传递long型-1触发异常的解决方法

问题原因及正确实现

异常触发根因

触发异常的核心原因是 NSDictionary 没有 integerForKey: 实例方法,该方法是NSUserDefaults的专属API。你存在obj(字典类型)中的code是NSNumber对象,不能直接通过不存在的方法读取。

正确实现步骤

  • 调整error回调块内的code取值逻辑
    从字典中先取出NSNumber类型的code对象,再调用integerValue转换为NSInteger类型,增加类型校验逻辑避免非字典场景崩溃,修改后代码如下:
- (void)sendInappropriateNewsfeedComment:(NSString *)comment newsfeedEventId:(NSString *)newsfeedEventId completion:(void (^)(NSString *, NSInteger))completion error:(void (^)(NSString *, NSInteger))error {
    PAInappropriateNewsFeedRequest *inappropriateNewsfeedRequest = [[PAInappropriateNewsFeedRequest alloc] initWithComment:comment newsfeedEventId:newsfeedEventId];
    [inappropriateNewsfeedRequest executeWithCompletionBlock:^(id obj) {
        completion(@"SUCCESS", 1);
    } error:^(NSError *e, id obj) {
        // 类型校验,避免obj不是字典时崩溃
        if (![obj isKindOfClass:[NSDictionary class]]) {
            error(@"未知错误", -1);
            return;
        }
        NSString *message = [obj objectForKey:@"message"];
        NSInteger code = [[obj objectForKey:@"code"] integerValue];
        error(message, code);
    }];
}
  • error block的声明规范
    你当前的error block声明void (^)(NSString *, NSInteger)本身是合规的,符合回调传递错误描述+错误码的通用场景。如果要更贴合Objective-C开发惯例,可以优先传递原生NSError对象作为第一个参数,声明示例如下:
// 通用惯例写法的error block声明
void (^)(NSError *, NSString *, NSInteger)

额外优化点

可以增加空值兼容逻辑,避免字典中message为NSNull或者不存在时后续使用崩溃:

NSString *message = [obj objectForKey:@"message"] ?: @"请求失败";

内容的提问来源于stack exchange,提问作者JFortYork

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 22:45:07