Reading the code example for finding the first 30 odd numbers, I saw that there was used static NSMutableArray *odds = [[NSMutableArray alloc] init]; inside the method.
Why? What is the reason to use static there? What is the real life usage of static arrays inside the method?
A static variable inside a method (or function) is used to extend the lifetime of an object across multiple invocations of the the same method (or function).
However, without seeing the context surrounding the static variable you are referring to it is hard to give the exact answer.
In my previous post I intentionally wasn’t writing the whole code example from the book as I thought that since everyone in this forum talks about examples from this book then everyone has it. But OK, here it is:
-(NSArray *)odds {
static NSMutableArray *odds = [[NSMutableArray alloc] init];
int i = 1;
while ([odds count] < 30) {
[odds addObject:[NSNumber numberWithInt:i]];
i += 2;
}
return odds;
}
If this method had the type (void) then it would be logical to put the array pointer as static. But the method is not of (void) type, that is why I don’t understand why we need it to be static. I am still new to Objective-C so I might be missing something.
Best regards,
Igor
Here is why: there is a bit of high-level code optimisation going on here.
When the method runs the very first time, it creates the array, fills it with thirty odd numbers, and returns it. Next time around, it will simply return the same array without having to recompute the numbers (Since the array is static, it is be kept alive as long as the program containing this piece of code is alive.)
You could write this piece of code without making the array static, but then each time the method is invoked it will make a fresh start: create the array, fill it with the same numbers, and return it. But this is just a waste of energy! So it makes sense to use a static array.
I am sure the BNR book will explain this, it may be in some other chapter.
[quote=“RunesReader”]Reading the code example for finding the first 30 odd numbers, I saw that there was used static NSMutableArray *odds = [[NSMutableArray alloc] init]; inside the method.
Why? What is the reason to use static there? What is the real life usage of static arrays inside the method?
Reagrds,
Igor[/quote]
Igor,
Are you looking at 2nd Edition (printed), page 183? My copy does not include “static” in the code example.