Categories

804 views
768 views

Published on

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
804
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
7
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Categories

    1. 1. Categories
    2. 2. Categories@interface NSString (MyExtension)-(NSString *)randomizeCharacters;@end//in codeNSString *stringToScramble = @”Tom Marvolo Riddle”NSString *scrambledString = [stringToScramble randomizeCharacters];
    3. 3. When should you use a category?
    4. 4. Categories• Extend classes without subclassing.• Create informal protocols.• Spread implementation over multiple files.• Simply development when multiple programmers are working on the same file.• Fix bugs in classes when you don’t have access to the source (in a last resort).
    5. 5. Some Cocoa classesare “class clusters” so subclassing is very difficult (NSString, NSArray, etc).
    6. 6. Sometimes, Apple uses “informal protocols.” (categories with no implementation)-(void)awakeFromNib;
    7. 7. (Maybe this is obsolete.)@protocol MyProtocol@optional:-(void)thisMethod;-(void)thatMethod;@end
    8. 8. Anonymous Categories are like private methods.@implementation MyClass()-(void)methodThatIWantToBePrivate;@end
    9. 9. But not really. (The Objective-C runtime isn’t that secure.)@implementation MyClass()-(void)methodThatIWantToBePrivate;@end// in another classMyClass *myClass = [[MyClass alloc] init];[myClass methodThatIWantToBePrivate]; // calls it
    10. 10. Be Careful About• Overriding existing methods• Causing conflicts with other categories (if two categories implement the method with the same name, the result is on predictable)
    11. 11. Subclassing vs Categories• Many times, the difference is not clear-cut• Subclass when you need to add a property (but in iOS 5 categories can add properties)• Don’t subclass Class Clusters
    12. 12. One example when I use categories is using Core Data. Core Data will auto generate class files. If I want to add methods to thoseclasses, I add them in a category so that, if I need to regenerate the classes, they won’t overwrite my changes.

    ×