如何初始化自定义类?

Dec*_*nna -3 iphone initialization objective-c ios

我的目标C非常生疏,真的不记得如何在创建时在自定义类中启动变量.

所有错误(id)init:

*缺少类型说明符,默认为'int'(警告)

*类型名称需要说明符或限定符

*预期';' 在声明清单的最后

#import "Seat.h"

@implementation Seat
{
    (id)init
    {
        self = [super init];
        player = NULL;
        position = -1;
        state = "empty";
    }
}

@end
Run Code Online (Sandbox Code Playgroud)

对不起,如果这看起来很简单,它看起来很简单,我找不到太多.谢谢

das*_*ght 5

你遗漏了一些东西:

-(id)init // A minus says it's an instance method
{
    if (self = [super init]) { // You should check the return value of [super init]
        player = NULL; // Should this be nil?
        position = -1;
        state = "empty"; // Should this be @"empty"?
    }
    return self; // You need to return self
}
Run Code Online (Sandbox Code Playgroud)

如果player是Objective C对象,而不是C指针,则更常规的是分配nil而不是NULL.字符串文字也是如此:如果stateNSString *,你应该分配@"empty"给它.

哦,@implementation不应该用花括号括起来:@end令牌足以找到实现块结束的位置.


Kun*_*ani 5

在右侧实用程序部分,检查下半部分代码段库.搜索'init'关键字.拖放代码

.在此输入图像描述