0

我想实现一个类集群(使用 ARC),但是 clang 妨碍了我。这是一个返回另一个类的具体实例的 init 方法 - 这是类集群的点:

@implementation PlaceholderServer
- (Server *) init {
    MockServer *concreteServer = [[MockServer alloc] init];
    return concreteServer;
}
@end

铿锵声抱怨return声明:

warning: incompatible pointer types returning 'MockServer *__strong' from a function with result type 'PlaceholderServer *' [-Wincompatible-pointer-types]

我理解该警告的原因:init被clang识别为属于init应该返回实现类(或者可能是子类)实例的方法家族。在类集群中通常不是这种情况,其中要实例化的实际具体类可能会因任何条件而异。

clang 提供了一个注释来覆盖方法族的自动识别:__attribute__((objc_method_family(FAMILLY))),其中 family 可以是alloccopyinitmutableCopy或中的一个new。也可以是none,文档说:“如果 family 是none,则该方法没有族,即使根据其选择器和类型,它会被认为有一个族。”

不幸的是,我无法让它在我的情况下工作。如果我将以下声明添加到@interface

- (SGIServer *) init __attribute__((objc_method_family(none)));

然后警告不会消失。如果我将属性添加到实现中:

- (Server *) init __attribute__((objc_method_family(none)))
{
    MockServer *concreteServer = [[MockServer alloc] init];
    return concreteServer;
}

然后警告不会消失我也得到一个错误:

error: method was declared as an 'init' method, but its implementation doesn't match because its result type is unrelated to its receiver type
- (SGIServer *) init __attribute__((objc_method_family(none)))
^

如果我两者都做,最初的警告不会消失,但我会收到一个额外的警告:

warning: attributes on method implementation and its declaration must match [-Wmismatched-method-attributes]

所以我想我错过了一些基本的东西,但是什么?

这适用于 Xcode 4.3.2 或 Xcode 4.4DP2。

4

1 回答 1

0

不需要弄乱属性;你应该可以改为return (id) concreteServer;,切换到动态类型。

于 2012-05-23T20:48:57.470 回答