有没有办法在NSArray上的类别中使用ObjectType?

Pat*_*ick 21 generics objective-c

我一直在尝试在NSArray上创建一个类别并查看NSArray的接口我假设添加一个返回ObjectType的方法是:

// interface
- (nullable ObjectType)giveMeAnObject;

// implementation
- (nullable ObjectType)giveMeAnObject
{
    ObjectType object = nil;
    return object;
}
Run Code Online (Sandbox Code Playgroud)

但是这不起作用,我在返回类型中收到错误消息Expected')'.

jtb*_*des 28

看起来你可以在接口中使用轻量级泛型,但不能在实现中使用.

@interface NSArray<ObjectType> (MyAdditions)

- (nullable ObjectType)giveMeAnObject; // specify return type

@end


@implementation NSArray (MyAdditions)

- (id)giveMeAnObject // use id for the implementation
{
    return nil;
}

@end
Run Code Online (Sandbox Code Playgroud)

如果您希望在块中查看增强请求,则可能需要提交增强请求@implementation.