不确定(id)init解释

时间:2014-03-31 15:46:27

标签: ios init

所以这是相当初学者,但我正在努力真正掌握这个概念。所以在我的示例代码中,我有一个Init方法,在.m的开头定义了两个常量:

#define NUM_TOP_ITEMS 5
#define NUM_SUBITEMS 6

- (id)init {
    self = [super init];

    if (self) {
        topItems = [[NSArray alloc] initWithArray:[self topLevelItems]];
        subItems = [NSMutableArray new];
        currentExpandedIndex = -1;

        for (int i = 0; i < [topItems count]; i++) {
            [subItems addObject:[self subItems]];
        }
    }
    return self;
}

这里的init方法是什么?我可以在他们单独的alloc / init方法中启动两个常量吗?这里任何清晰度都会很棒!感谢

2 个答案:

答案 0 :(得分:2)

好的,一行一行......

#define NUM_TOP_ITEMS 5 // defining a macro for the number 5
#define NUM_SUBITEMS 6 // and 6

- (id)init
{
    self = [super init]; // here you are initialising the object by calling the super class method
    // this is important as you still want the functionality/properties etc... from the super class.

    if (self) { //check the object actually exists.
        topItems = [[NSArray alloc] initWithArray:[self topLevelItems]]; //This looks like it's running a method called topLevelItems
        // that returns an NSArray. You are then saving it in an iVar (I guess)
        subItems = [NSMutableArray new]; // this creates a new mutable array in an iVar called subItems
        currentExpandedIndex = -1; // this sets an iVar int value

        for (int i = 0; i < [topItems count]; i++) { // set up a for loop for the topItems array
            [subItems addObject:[self subItems]]; //...wat?
            // not quite sure what's going on here.
            // I don't think it's doing what you think it's doing
        }
    }
    return self; // return the object whether it has been allocated successfully or not.
}

答案 1 :(得分:0)

使用#define定义的常量就像是在编译时发生的标记的搜索和替换。这是C pre-processor,它意味着像这样的代码,

#define NUM_TOP_ITEMS 5 + 1
int i = NUM_TOP_ITEMS + NUM_TOP_ITEMS;

被预处理为类似的东西,

int i = 5 + 1 + 5 + 1;

在下一个编译步骤发生之前。