Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Categories and Protocols 101: What are they and how can they be used?

syreinrage
November 19, 2013

Categories and Protocols 101: What are they and how can they be used?

Have you ever wanted to add methods to existing core classes? Well if you didn't before you will now. In this talk, we will be exploring the wonderful world of categories. I will be going over the basics of what categories are and how they can be used. Beginning from the benefits of adding class functionality to some development techniques of breaking up class implementations into manageable segments. So, rather than continuously relying on creating new classes or subclassing to provide additional lightweight functionality, join us and learn about Categories.

Protocols provide a way to define a set of methods that a class should implement. Understanding them and using them help make code more maintainable and easier for collaboration. The second portion of the talk will be covering protocols, when to use them, and how they can be helpful in your programs.

Jazmine is an iOS Developer who, after training in Cupertino at Apple's Cocoa Camp, went on to working for RR Donnelley in Midtown Atlanta. Graduate of Spelman College and former/secretly current robotics geek

syreinrage

November 19, 2013
Tweet

Other Decks in Programming

Transcript

  1. Categories and Protocols 101 What are they and how can

    they be used? Presenter: Jazmine Miller
  2. Outline • What are Categories - Use Cases - Implementation

    - Pros and Cons - categories vs other options • What are Protocols - Use Cases - Implementation - Delegation vs Notification • References & Suggestions
  3. What are Categories? ‣ Define additional methods of an existing

    class - (including those with source you don’t have access to)
  4. Using Categories ‣ Extend the functionality of classes you don’t

    have access to. ‣ Don’t want to deal with subclassing ‣ Want functionality added to be inherited by subclasses ๏ NSString > NSMutableString, etc
  5. Using Categories ‣Split up a class’s implementation across multiple files

    ‣Creating forward declarations of certain methods
  6. Splitting an Implementation • /System/Library/Frameworks/AppKit.framework/Headers/ • NSTextView • @interface NSTextView

    (NSCompletion) • @interface NSTextView (NSPasteboard) • @interface NSTextView (NSDragging) • @interface NSTextView (NSSharing) • @interface NSTextView (NSTextChecking) • @interface NSTextView (NSQuickLookPreview) • @interface NSTextView (NSTextView_SharingService)
  7. Categories Limitations • Can’t add new instance variables to a

    class - Cheats: fancy global dictionaries or even fancier associated objects. - But is it worth it ? • any name collisions = category overwrite
  8. Categories vs Subclassing • Categories useful for altering all instances

    of a class with minimal code • Better used for adding functionality only • Subclassing is useful for for altering certain instances and maintaining original methods for others • Better used for adding customization
  9. Categories vs Class Extensions • The compiler won’t synthesize any

    instance variable, or property accessor methods. • Possible to write accessor methods in the category implementation - can’t store a value for that property unless it’s already stored by the original class •Can only be added to a class you have source code for at runtime •implemented in @implementation block - can’t extend Cocoa Classes ex: NSString, etc
  10. Private Categories vs Class Extensions @interface MasterViewController () - (void)updateData;

    - (void)sortData; @end @interface MasterViewController (Private) - (void)updateData; - (void)sortData @end
  11. Private Categories vs Class Extensions @interface MasterViewController () @end @interface

    MasterViewController (Private) - (void)updateData; - (void)sortData @end
  12. Private Categories vs Class Extensions @interface MasterViewController () @property (nonatomic,

    strong, readwrite) NSArray *items; @end • Can declare properties inside extensions • Allow you to have public readonly properties • Override properties internally @interface MasterViewController : UIViewController < ... > { ... } @property (nonatomic, strong, readonly) NSArray *items; @end .h file .m file
  13. Categories vs Class Extensions • Can declare properties inside extensions

    • Allow you to have public readonly properties and private writable • Override properties internally • Don’t declare ‘Private’ Categories. Its better to use class extensions
  14. Protocols ‣ a defined set of properties and methods that

    a conforming object must (if not optional) implement. - (used to declare methods and properties that are independent of any specific class.)
  15. Why use Protocols ‣To declare methods for others to implement

    ‣ Declare the public interface to a class while hiding the nature of the class itself ‣ To mark similarities between classes that are not part of the same inheritance tree ‣Inter-object Communication
  16. Protocols Delegate Pattern •Define an interface that any object can

    conform to in order to become the delegate of another object. ViewController UITableView (Delegate) tableView:{...} numberOfSectionsInTableView:(UITableView *)tableView how many sections do i need to draw? return (NSInteger) tableView:{...} numberOfRowsInSection:(NSInteger)section how many rows do i need to draw? return (NSInteger)
  17. Data Source Protocol @protocol NSTableViewDataSource <NSObject> @optional #pragma mark -

    #pragma mark ***** Required Methods (unless bindings are used) ***** - (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView; /* This method is required for the "Cell Based" TableView, and is optional for the "View Based" TableView. If implemented in the latter case, the value will be set to the view at a given row/column if the view responds to -setObjectValue: (such as NSControl and NSTableCellView). */ UITableView Data Source • /System/Library/Frameworks/AppKit.framework/Headers/
  18. Data Source Protocol - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the

    number of sections. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section { // Return the number of rows in the section. // If you're serving data from an array, return the length of the array: return [dataArray count]; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } // Set the data for this cell: cell.textLabel.text = [dataArray objectAtIndex:indexPath.row]; cell.detailTextLabel.text = @"More text"; cell.imageView.image = [UIImage imageNamed:@"flower.png"]; // set the accessory view: cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; return cell; } UITableView Data Source
  19. Delegation vs Notification • Notification is used to broadcast messages

    to possibly several recipients unknown from the sender • Delegation is used to send messages to a single known recipient acting on behalf of the sender • Notifications are generally better for notifying the UI changes across threads (strongly discourages with delegates)