Posted By

zopebie on 08/14/12


Tagged

Objective-c ios


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

gurin2014
zopebie
espinallab
cnathan


Categories


 / Published in: Objective C
 

A category in Objective-C allows you to add methods to an existing class without the need to subclass it. You can also use a category to override the implementation of an existing class.

  1. Simply create a new class file and code it as follows:
  2.  
  3. //--Utils.h--
  4.  
  5. #import <Foundation/Foundation.h>
  6.  
  7. //---NSString is the class you are extending---
  8. @interface NSString (stringUtils)
  9.  
  10. //---the method you are adding to the NSString class---
  11. -(BOOL) isEmail;
  12.  
  13. @end
  14.  
  15. //--Utils.m--
  16. #import "Utils.h"
  17. @implementation NSString (Utilities)
  18. - (BOOL) isEmail {
  19. NSString *emailRegEx =
  20. @"(?:[a-z0-9!#$%\\&�*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&�*+/=?\\^_`{|}"
  21. @"~-]+)*|¢ï¿½ï¿½(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
  22. @"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*¢ï¿½ï¿½)@(?:(?:[a-z0-9](?:[a-"
  23. @"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
  24. @"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
  25. @"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
  26. @"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
  27.  
  28. NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
  29.  
  30. return [regExPredicate evaluateWithObject:self];
  31. }
  32. @end
  33.  
  34.  
  35.  
  36. You can then test for the validity of an e-mail address using the newly added method:
  37.  
  38. NSString *email = @"[email protected]";
  39. if ([email isEmail])
  40. NSLog(@"Valid email");
  41. else
  42. NSLog(@"Invalid email");

Report this snippet  

You need to login to post a comment.