2

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?

1
  • 1
    It sounds like you need an array. Also, those casts to (id) are superfluous and horrible. Commented Jan 18, 2014 at 21:42

1 Answer 1

4

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"];
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, this is exactly what I was looking for! Sorry for bad code I am new to objective-c.
Wait, using the second way I get the yellow flag assigning to 'id uitextfielddelegate ' from incompatible type *const __strong'
1 line only :: setValue:forKeyPath: [self.arrayOfDays setValue:self forKeyPath:@"delegate"];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.