There are several approaches to this kind of thing. (None of the code here has been tested or even compiled.)
The most obvious is a simple method:
- (void)setFormValueFromSegmentedControl:(UISegmentedControl *)seg forKey:(NSString *)key {
if (seg.selectedSegmentIndex !=-1) {
[self.form setValue:[seg titleForSegmentAtIndex:seg.selectedSegmentIndex] forKey:key];
}
}
Now your code simplifies to:
[self setFormValueFromSegmentedControl:self.title forKey:@"titleKey"];
[self setFormValueFromSegmentedControl:self.author forKey:@"authorKey"];
...
Personally, I like this because it's so simple and obvious to read with a minimum of magic. But there are other solutions if even that block got unwieldy.
You can do something like @Cyrille and @H2CO3 are suggesting:
for (NSString *key in [@"title", @"author", ...]) {
UISegmentedControl *seg = [self valueForKey:key];
if (seg.selectedSegmentIndex != -1) {
NSString *formKey = [key stringByAppendingString:@"Key"];
[self.form setValue:[seg titleForSegmentAtIndex:seg.selectedSegmentIndex] forKey:formKey];
}
}
You could also use a tag
on the control to indicate which form key it applies to (you can configure tags in IB or using setTag:
in code). So title
would have a tag of 0, author
would have a tag of 1, etc.
NSArray *formKeyForTag = @[@"titleKey", @"authorKey", ...];
for (UISegmentedControl *seg = [... IBOutletCollection of controls ...]) {
if (seg.selectedSegmentIndex != -1) {
NSString *formKey = formKeyForTag[seg.tag];
[self.form setValue:[seg titleForSegmentAtIndex:seg.selectedSegmentIndex] forKey:formKey];
}
Or you could add an associated object to the segmented control, pointing to the form key. See What is objc_setAssociatedObject() and in what cases should it be used? for more on that. (I happen to love associated objects…)
Or you could use an NSDictionary
to keep the mappings.
So lots of options. But I kind of like the simple method at the top. It's the most obvious.