Question

So this is fairly beginner, but I'm trying to really grasp this concept. So in my sample code I have an Init method with two Constants defined at the beginning of the .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;
}

What is the init method doing here? Could i initiate the two constants in their separate alloc/init methods? Any clarity here would be great! thanks

Was it helpful?

Solution

OK, line by line...

#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.
}

OTHER TIPS

Constants defined using #define are like a search and replace for tokens which happens at compile time. This is the C pre-processor, it means that code like this,

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

gets pre-processed to something like this,

int i = 5 + 1 + 5 + 1;

before the next compilation step happens.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top