user1953754 user1953754 - 3 months ago 4
Objective-C Question

Using a string as name to set property values

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?


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


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"];