Skip to content

Instantly share code, notes, and snippets.

@iljaiwas
Last active August 29, 2015 14:11
Show Gist options
  • Save iljaiwas/e667b7e4dd288bc1ce73 to your computer and use it in GitHub Desktop.
Save iljaiwas/e667b7e4dd288bc1ce73 to your computer and use it in GitHub Desktop.
IHMenuItemValidator
//
// IHMenuItemValidator.m
// GarageSale
//
// Created by ilja iwas on 12.12.14.
//
//
#import "IHMenuItemValidator.h"
@implementation IHMenuItemValidator
/** If you have Cocoa controller or delegate classes that are so big (yes, I know, bad practice),
that your validateMenuItem: method spans several screen pages, this method helps you to:
a) break validateMenuItem: into several smaller pieces of code
b) but your validation code right next to action method
To use it, change your validateMenuItem: method to look like this:
- (BOOL)validateMenuItem:(NSMenuItem *)item
{
return [IHMenuItemValidator validateMenuItem:item withTarget:self];
}
In case, e.g. validateMenuItem is called for the action 'delete:' , the code looks for a method called validateDelete:(NSMenuItem*) menuItem. Implement your validation code in that method and say goodbye to gigantic if/else if/ constructs.
*/
+ (BOOL) validateMenuItem:(NSMenuItem *)inMenuItem withTarget:(id) inTarget
{
NSString *selectorName = NSStringFromSelector(inMenuItem.action);
NSString *firstLetter = [selectorName substringToIndex:1];
firstLetter = firstLetter.uppercaseString;
selectorName = [firstLetter stringByAppendingString:[selectorName substringFromIndex:1]];
NSString *validateSelectorName = [@"validate" stringByAppendingFormat:@"%@",selectorName];
SEL validationSelector = NSSelectorFromString(validateSelectorName);
if ([inTarget respondsToSelector:validationSelector])
{
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[inTarget class] instanceMethodSignatureForSelector:validationSelector]];
invocation.target = inTarget;
invocation.selector = validationSelector;
[invocation setArgument:&inMenuItem atIndex:2];
[invocation invoke];
BOOL result;
[invocation getReturnValue:&result];
return result;
}
return YES;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment