Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Few questions on Crystal Ball

'''

  • (NSArray*) predictions { if (_predictions == nil) { _predictions = [[NSArray alloc] initWithObjects: @"It is certain", @"It is decidedly so", @"All signs point to yes", @"The stars are not alligned", @"My reply is no", @"It is doubtful", @"Better not tell you now", @"Concentrate and ask again", @"Unable to answer now", nil]; } return _predictions; '''

So firstly, why do we need to do if (_predictions == nil) ? Isn't that just saying, if there is nothing already in the array, make this array below? Surely we don't need that line, and we could just write out the array without the if statement?

Whats the return _predictions at the end to do with? I don't seem to remember a video actually telling us what the return does, and why it's used here?

Thanks for any help.

1 Answer

The reason we are adding the if statement is that when the app launches for the first time then we will allocate and initialize the array. Because the first the app launches the array will be empty and then every time the app is run since we have already allocated memory to the array and initialized it we will not be wasting time and memory in that process. and so the app will run quickly..

Now coming to the return statement : They have talked about this in the c fundamentals video. Basically, return statement is used to return some value from a method. Since we have created another model class and this method is created in the model class, so we are calling this method from the view controller class. So, thats why we are returning the allocated predictions array to the viewcontroller class.

This is what my understanding is.... I hope it helps you. I would highly recommend you to first go through the C and objective C concepts.