2
static NSMutableDictionary * allTheSingletons;
@implementation BGSuperSingleton

+(instancetype)singleton
{
    return [self singleton1];
}
+(id) singleton1
{
    NSString* className = NSStringFromClass([self class]);

    if (!allTheSingletons)
    {
        allTheSingletons = NSMutableDictionary.dictionary;
    }

    id result = allTheSingletons[className];

    PO(result);
    if (result==nil)
    {
        result = [[[self class] alloc]init];
        allTheSingletons[className]=result;
    }
    return result;
}

BGSuperSingleton は、すべてのシングルトン クラスの親である必要があります。

次に、サブクラスの 1 つで行います。

+(NSPredicate *)withinASquare:(double)distance{
    CLLocation * anchorWeUsed=[self singleton].mapCenterLocation; //Error map center is not of type ID
    return [self withinASquare:distance fromLocation:anchorWeUsed];
}

CLANG は singleton がタイプであることを理解せず+(instancetype)、代わりにタイプが id であると考えているようです。

私は何が欠けていますか?

selfただし、MySubSingletonClass(コンパイル時に既知のものである)に置き換えることは機能します。

説明はありますか?

4

1 に答える 1

1

確かではありません(そして、以下はすべて私の仮定にすぎません)が、コンパイル時にコンパイラは のクラスを認識していないようです[self singleton1]ドキュメントで述べられているように(その動作instancetypeも推定すると):

...そして、その戻り値の型がそのクラスの型と互換性がある場合、メソッドには関連する結果の型があります...

つまりsingleton1、未知のクラスのオブジェクトを返し、クラスとsingleton互換性のないオブジェクトを返すと見なすためBGSuperSingleton(コンパイル時に不明である限り)、関連する結果の魔法はここでは機能しません。

それに興味があり、チェックしました:

+ (NSPredicate*) withinASquare: (double)distance {
    CLLocation* anchorWeUsed = [[self alloc] init].mapCenterLocation; // Error map center is not of type ID
    return [self withinASquare:distance fromLocation:anchorWeUsed];
}

alloc関連する結果クラスをinit返しますが、エラーはまだあります。助けになったのは:

+ (NSPredicate*) withinASquare: (double)distance {
    BGSuperSingleton* bgSuperSingleton = [[self alloc] init]; // class is known at compile time
    CLLocation* anchorWeUsed = bgSuperSingleton.mapCenterLocation; // no error here
    return [self withinASquare:distance fromLocation:anchorWeUsed];
}

私はまだこれに興味があり、誰かが私の仮定を承認または修正してくれることを願っています.

于 2013-04-23T08:19:01.090 に答える