Objective C没有init的Constructer

Cal*_*YSR 0 initialization objective-c ios

当我创建自定义类时,我希望能够在构建类的实例后跳过代码的alloc init部分.与它的完成方式类似:

NSString * ex = [NSString stringWithFormat...]; 
Run Code Online (Sandbox Code Playgroud)

基本上我已经使用自定义初始化方法设置了类来设置我的基本变量.然而,当我在前端并实际制作这些小动物时,我不得不说:

[[Monster alloc] initWithAttack:50 andDefense:45]; 
Run Code Online (Sandbox Code Playgroud)

而且我宁愿能说

[Monster monsterWithAttack:50 andDefense:45]; 
Run Code Online (Sandbox Code Playgroud)

我知道删除alloc部分是一个简单的愚蠢的事情,但它使代码更具可读性,所以我更喜欢这样做.我最初尝试改变我的方法

-(id)initWithAttack:(int) a andDefense:(int) d 
Run Code Online (Sandbox Code Playgroud)

-(id)monsterWithAttack:(int) a andDefense:(int) d 
Run Code Online (Sandbox Code Playgroud)

然后改变我的self = [super init],self = [[super alloc] init];但显然不起作用!有任何想法吗?

Kev*_*vin 6

你必须创建一个方法

+(id)monsterWithAttack:(int) a andDefense:(int) d 
Run Code Online (Sandbox Code Playgroud)

您在其中创建,初始化和返回实例(并且不要忘记您的内存管理):

+(id)monsterWithAttack:(int) a andDefense:(int) d {
    // Drop the autorelease IF you're using ARC 
    return [[[Monster alloc] initWithAttack:a andDefense:d] autorelease];
}
Run Code Online (Sandbox Code Playgroud)


Cod*_*aFi 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;
    }
Run Code Online (Sandbox Code Playgroud)