user5465320
user5465320

Reputation: 739

How to return a id<protocol_type> in iOS

I have a function , return a protocol.

But Xcode waring: [Returning 'HpadMoblieCollectorBooleanResult *'__strong from a function with incompatible result type 'id' ]

-----------sep line ---------------------

Question detail :

HpadCollectorBooleanResult.h

@protocol HpadCollectorBooleanResult <NSObject>
- (void) result:(void(^)(BOOL))block ; 
@end

I have a Class to implement HpadCollectorBooleanResult protocol , the Class is HpadMoblieCollector .

HpadMoblieCollector.h

    #import "HpadCollectorResult.h"

    @interface HpadMoblieCollector : NSObject

    // clear All
    - (id<HpadCollectorBooleanResult>) favorite_ajax_clear ;

    @end 

and the .m file is

HpadMoblieCollector.m

@interface HpadMoblieCollectorBooleanResult<HpadCollectorBooleanResult> : NSObject
{
    void(^_result)(BOOL) ;
    BOOL isExe ;
    BOOL resultFlag ;
}

@end

@implementation HpadMoblieCollector

 // 清空手机收藏夹
- (id<HpadCollectorBooleanResult>) favorite_ajax_clear
{
    HpadMoblieCollectorBooleanResult *result = [[HpadMoblieCollectorBooleanResult alloc] init] ;
    return result ;  

// Xcode waring: 
// Returning 'HpadMoblieCollectorBooleanResult *'__strong from a function 
// with incompatible result type 'id<HpadCollectorBooleanResult>' 
}

@end

You can see , the method "- (id< HpadCollectorBooleanResult >) favorite_ajax_clear" have an error , I cannot solve the problem .

1、Can you tell me why the Xcode send a warning message ?

2、Can you help me to resolve it ?

Upvotes: 0

Views: 112

Answers (2)

orkoden
orkoden

Reputation: 20006

id<HpadCollectorBooleanResult> means an object (id) that implements the protocol HpadCollectorBooleanResult.

You are creating an instance of the class HpadMoblieCollectorBooleanResult with alloc [init]].

If HpadMoblieCollectorBooleanResult is a class you need to change the return type of your method to - (HpadMoblieCollectorBooleanResult *) favorite_ajax_clear

If HpadMoblieCollectorBooleanResult is a protocol you need to create a new class that implements that protocol. Then you can return an instance of that class. In this case it's a protocol.

@interface MyClass : NSObject <HpadCollectorBooleanResult>
- (void) result:(void(^)(BOOL))block
{
}
@end

Upvotes: 0

sahara108
sahara108

Reputation: 2859

Why @interface HpadMoblieCollectorBooleanResult<HpadCollectorBooleanResult> : NSObject?

Change it to @interface HpadMoblieCollectorBooleanResult : NSObject<HpadCollectorBooleanResult> and the warning should go away.

Upvotes: 1

Related Questions