2

次のようなクラスメソッドを持つクラスがあります。

+ (id)itemWithTitle:(NSString *)title target:(id)target action:(SEL)action
{
    self = [[self alloc] initWithTitle:title target:target action:action];

    return self;
}

手動参照カウントでは問題なく動作しますが、ARC で使用しようとすると、「クラス メソッドで自分自身に割り当てることはできません」というエラーが表示されます。これを修正する方法はありますか?

4

2 に答える 2

6

これはARCとは関係ないと思います。違いは、ARC を使用すると、コンパイラが警告/エラーを表示することです。

一般に、クラス メソッド (- ではなく + で始まり、別の方法で呼び出されるもの) では、self は特定のオブジェクトを参照しません。クラスを指します。[self alloc] を使用すると、サブクラス化されているかどうかに関係なく、まさにそのクラスのオブジェクトを作成できます。これがインスタンス メソッド [[self class] alloc] であれば、まったく同じように機能します。しかし、あなたは正当な理由でクラスメソッドにいます。

この場合、結果を返さないのはなぜですか?

+ (id)itemWithTitle:(NSString *)title target:(id)target action:(SEL)action
{
    return [[self alloc] initWithTitle:title target:target action:action];
}

クラス名が Foo の場合は、次のようになります。

+ (id)itemWithTitle:(NSString *)title target:(id)target action:(SEL)action
{
    Foo *newMe = [[self alloc] initWithTitle:title target:target action:action];
    // Here you have access to all properties and methods of Foo unless newMe is nil.
    return newMe;
}

または、Foo のメソッドとプロパティにアクセスすることなく、より一般的に:

+ (id)itemWithTitle:(NSString *)title target:(id)target action:(SEL)action
{
    id newMe = [[self alloc] initWithTitle:title target:target action:action];
    return newMe;
}
于 2013-02-25T16:51:17.267 に答える
2

selfARC 以前のコードでキーワードを誤用してはいけません。このように見えるはずでした。

+ (id)itemWithTitle:(NSString *)title target:(id)target action:(SEL)action
{
    MyClass* obj = [[[MyClass alloc] initWithTitle:title target:target action:action] autorelease];

    return obj;
}

ARC では、唯一の違いは、autorelease.

于 2013-02-25T16:50:58.020 に答える