【问题标题】:Objective C - Cannot initialize return object of type 'id'Objective C - 无法初始化“id”类型的返回对象
【发布时间】:2015-12-07 02:26:48
【问题描述】:

我在我的项目中使用了我朋友的代码,但我收到了这个错误(他的代码在他的项目中没有错误。)

错误:Cannot initialize return object of type 'id'with an rvalue of type 'AsyncTaskResult_e'

.m 文件发生错误(返回失败;)

这是.h文件

#ifndef AsyncTask_h
#define AsyncTask_h

#import <Foundation/Foundation.h>

typedef enum AsyncTaskResult_e {
    Success,
    Fail
}

AsyncTaskResult_t;

@protocol AsyncTaskInterface

@required
-(void)preExecute:(id)parameters;
-(id)doInBackground:(id)parameters;
-(void)postExecute:(id)result;

@end

// This interface is imitated AsyncTask of Android
@interface AsyncTask : NSObject<AsyncTaskInterface>

-(void) executeParameters:(id)parameters;

@end

#endif /* AsyncTask_h */

这是.m文件

#import "AsyncTask.h"

@implementation AsyncTask

-(void) executeParameters:(id)parameters {
    [self preExecute:parameters];
    __block id result;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        result = [self doInBackground:parameters];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self postExecute:result];
        });
    });
}

-(void)preExecute:(id)parameters {
    // Run on main thread (UIThread)
}

-(id)doInBackground:(id)parameters {
    // Run on async thread (Background)
    return Fail;
}

-(void)postExecute:(id)result {
    // Run on main thread (UIThread)
}

@end

我是否缺少实现此代码的内容?

【问题讨论】:

  • Fail 是一个枚举,返回它的函数返回 id 这是一个对象。枚举不能转换为对象。
  • 为什么投反对票?问一个你不知道的问题是错误的吗?
  • @user3423040 您的问题没有理由投反对票,也没有理由投赞成票。您的问题显示了相关代码,它提出了一个明确的问题,并解释了您遇到的错误。

标签: objective-c enums


【解决方案1】:

这确实是它在锡上所说的。函数 doInBackground 返回一个 id,但 AsyncTaskResult_e 的类型是一个 int。因为整数是值类型,所以它们不能存储在 id (这是一个通用的目标 C 对象)中,除非先将它们装箱,然后将它们转换为 NSNumber。您可以使用@() 运算符来执行此操作,但除非您真的想在这里返回一个对象,否则最好将函数的返回类型更改为 AsyncTaskResult_e。

为了更好地解释错误,右值通常只是任何赋值表达式右侧的东西。 This article 更详细。

【讨论】:

    猜你喜欢
    • 2014-10-07
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多