0

カスタムクラスを作成するときは、クラスのインスタンスを作成するときに、コードのallocinit部分をスキップできるようにしたいと思います。それがどのように行われるかに似ています:

NSString * ex = [NSString stringWithFormat...]; 

基本的に、基本変数を設定するためのカスタム初期化メソッドを使用してクラスを設定しています。しかし、私がフロントエンドにいて、実際にこれらの生き物を作っているとき、私は言わなければなりません:

[[Monster alloc] initWithAttack:50 andDefense:45]; 

そして私はむしろ言うことができたい

[Monster monsterWithAttack:50 andDefense:45]; 

alloc部分を削除するのは単純な愚かなことですが、コードが読みやすくなるので、そのようにしたいと思います。私はもともと自分の方法をから変更しようとしました

-(id)initWithAttack:(int) a andDefense:(int) d 

-(id)monsterWithAttack:(int) a andDefense:(int) d 

そして、に変更self = [super init]しますself = [[super alloc] init];が、それは明らかに機能しません!何か案は?

4

4 に答える 4

6

クラスメソッドを作成する必要があります

+(id)monsterWithAttack:(int) a andDefense:(int) d 

インスタンスを作成、初期化、および返す(そしてメモリ管理を忘れないでください):

+(id)monsterWithAttack:(int) a andDefense:(int) d {
    // Drop the autorelease IF you're using ARC 
    return [[[Monster alloc] initWithAttack:a andDefense:d] autorelease];
}
于 2012-07-07T22:08:40.520 に答える
6

必要なのは便利なコンストラクターです。これは、クラスの使用可能なインスタンスを返し、同時にそのクラスにメモリを割り当てるクラスメソッドです。

-(id)initWithAttack:(int)a andDefense:(int)d;
+(id)monsterWithAttack:(int)a andDefense:(int)d;

+(id)monsterWithAttack:(int)a andDefense:(int)d {
        //-autorelease under MRC
        return [[[self class] alloc] initWithAttack:a andDefense:d];
 }
 -(id)initWithAttack:(int)a andDefense:(int)d {
        self = [super init];
        if (self){
             //custom initialization
        }
        return self;
    }
于 2012-07-07T22:12:08.417 に答える
3

モンスタークラスのヘッダーでクラスファクトリメソッドを使用する必要があります。

+(id)monsterWithAttack:(int) attackValue andDefense:(int) defenseValue 

モンスタークラスの実装で

+(id)monsterWithAttack:(int) attackValue andDefense:(int) defenseValue {
    return [[[[self class] alloc] initWithAttack:attackValue andDefense:defenseValue] autorelease];
}

を使用すると[self class]、サブクラス化中に正しいディスパッチが保証されます。ARCを使用している場合は、このautorelease方法を回避できます

于 2012-07-07T22:14:04.353 に答える
2

このタイプのクラスメソッドはを使用しますautorelease

したがって、たとえば、次のように言うことができます。

+ (id)
monsterWithAttack:(int)  a
defense:(int)            d
{
    return [[Monster alloc] initWithAttack:a defense:d]
            autorelease];
}
于 2012-07-07T22:11:27.663 に答える