Reputation: 27
I have these big huge repetitive chunks of code in my project I am attempting to shrink them down. Take this piece example:
self.Day11.delegate = (id)self;
self.Day12.delegate = (id)self;
self.Day13.delegate = (id)self;
self.Day14.delegate = (id)self;
self.Day15.delegate = (id)self;
self.Day16.delegate = (id)self;
self.Day17.delegate = (id)self;
self.Day18.delegate = (id)self;
self.Day19.delegate = (id)self;
What I would like to do is make it that I can use a for loop or something similar to shrink it down like this:
for (int i = 1 ; i<=9; i++) {
NSString *var = [NSString stringWithFormat:@"Day1%d",i];
self.var.delegate = (id)self;
}
I know this doesn't work is there a possible way to do something like this?
Upvotes: 2
Views: 334
Reputation: 62052
No, no, no.
@property (nonatomic,strong) NSArray *arrayOfDays;
Now get rid of all those day objects and fill that self.arrayOfDays
with whatever all those individual day objects are...
Then...
for(int i=0; i<[self.arrayOfDays count]; ++i) {
[[self.arrayOfDays objectAtIndex:i] setDelegate: self];
}
Or even better, if all those objects are of the same type (I'll assume they're of type Day
), we can do:
for(Day *day in self.arrayOfDays) {
day.delegate = self;
}
Best (per Daij-Dan's comment):
[self.arrayOfDays setValue:self forKeyPath:@"delegate"];
Upvotes: 4