Objective C - 无法初始化'id'类型的返回对象

时间:2015-12-07 02:26:48

标签: objective-c enums

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

错误: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

我错过了实现此代码的内容吗?

1 个答案:

答案 0 :(得分:2)

这正是它在锡上所说的。函数doInBackground返回一个id,但AsyncTaskResult_e的类型是一个int。因为整数是值类型,所以它们不能存储在id(这是一个通用的目标C对象)中,而不是先将它们转换为NSNumber。你可以使用@()运算符来做到这一点,但除非你真的想要在这里返回一个对象,否则你最好将函数的返回类型更改为AsyncTaskResult_e。

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

相关问题