I’ve asked similar questions, but they all concerned using a block for a specific value of the array. This is a bit different, I want to fill in the values of an array at initialization using a block. Apart from subclassing NSArray to do this, is there another way similar to this:
In this scenario, I populate an array with the days of the week, where today is always in the middle. My “classic” way of doing this would be:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
NSMutableArray *test = [[NSMutableArray alloc] init];
for (int i = -3; i < 4; i++) {
[test addObject:[dateFormatter stringFromDate:[[NSDate date] dateByAddingTimeInterval:60*60*24*i]]];
}
Ideally, what I would like to do, is initialize an array and fill it with values which are assigned dynamically using a block, something like this:
NSArray *array = [[NSArray alloc] initWithObjects:^(){ for (int i = -3; i < 4; i++) {
return [dateFormatter stringFromDate:[[NSDate date] dateByAddingTimeInterval:60*60*24*i]];
}}, nil];
Now the above code creates nothing, and rightly so since method initWithObjects expects objects and not a block, and furthermore, the block would execute once, returning only one object. So is this possible/doable, or would I need to subclass NSArray to create a method something like initWithBlock ?
You don’t need to subclass NSArray to add a method to it. A category will do.
What you want is not possible with any of the current NSArray methods. And it won’t quite work as you drafted it in your question because the language doesn’t support multiple return values from a block (or function or method). So you would have to write a block that actually creates an NSArray and returns that. But if you do that, you might as well leave out the block and create the array straight away.