Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

ios - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...