Is there any way to simplify this method? Perhaps a way to && both statements together in one for- loop?
// Enable valid decimal buttons
- (IBAction)enableDecimalValues
{
for(UIButton *decimalButton in nonOctalValueCollection)
{
decimalButton.enabled = YES;
[decimalButton setAlpha:1];
}
for(UIButton *decimalButton in nonBinaryValueCollection)
{
decimalButton.enabled = YES;
[decimalButton setAlpha:1];
}
}
There is nothing "wrong" with your code, per se. What you have here is clarity; a reader can quickly see and understand what is happening.
Alternatives require allocating memory and copying objects, just so you can have 1 loop. But in the end, the performance is worse (strictly speaking).
But, if you insist, how about this:
NSMutableArray *buttons = [[[NSMutableArray alloc] initWithArray:nonOctalValueCollection] autorelease];
[buttons addObjectsFromArray:nonBinaryValueCollection];
for(UIButton *decimalButton in buttons)
{
decimalButton.enabled = YES;
[decimalButton setAlpha:1];
}
(Leave off the autorelease
if you're using ARC.)
It seems to me that you are trying to make it DRY and the bit that is repeated is what is happening in the body of the loop. I don't see the need to allocate a new array just so you only have to iterate over one collection so I would do something like this
void (^block)(UIButton *button, NSUInteger idx, BOOL *stop) =
^(UIButton *button, NSUInteger idx, BOOL *stop) {
button.enabled = YES;
button.alpha = 1.0f;
};
[nonOctalValueCollection enumerateObjectsUsingBlock:block];
[nonBinaryValueCollection enumerateObjectsUsingBlock:block];
This DRY's it up and does not incur the additional allocation of the temporary array.
Think this is the most simple you can make it. Alternatively you could refactor the code to another method and pass both arrays to this method.
NSMutableArray *allButtons = [NSMutableArray array];
[allButtons addObjectsFromArray:nonOctalValueCollection];
[allButtons addObjectsFromArray:nonBinaryValueCollection];
for (UIButton *button in allButtons) {
button.enabled = YES;
button.alpha = 1;
}
How about:
- (IBAction)enableDecimalValues
{
NSArray *combinedArray =
[nonOctalValueCollection
arrayByAddingObjectsFromArray:nonBinaryValueCollection];
[combinedArray makeObjectsPerformSelector:@selector(setEnabled:)
withObject:[NSNumber numberWithBool:YES]];
[combinedArray makeObjectsPerformSelector:@selector(setAlpha:)
withObject:[NSNumber numberWithFloat:1.0f]];
}
Or:
- (IBAction)enableDecimalValues
{
NSArray *combinedArray =
[nonOctalValueCollection
arrayByAddingObjectsFromArray:nonBinaryValueCollection];
[combinedArray enumerateObjectsUsingBlock:
^(UIButton *button, NSUInteger idx, BOOL *stop)
{
button.enabled = YES;
button.alpha = 1.0f;
}];
}
Leading to:
- (IBAction)enableDecimalValues
{
[[nonOctalValueCollection
arrayByAddingObjectsFromArray:nonBinaryValueCollection]
enumerateObjectsUsingBlock:
^(UIButton *button, NSUInteger idx, BOOL *stop)
{
button.enabled = YES;
button.alpha = 1.0f;
}];
}