Objective-c Category (categories)

Source: Internet
Author: User

Category is one of the most commonly used functions in objective-c.

The category can add methods to existing classes without adding a subclass.

The standard syntax format for the category interface is as follows:

[CPP]View Plaincopy
    1. #import "class name. h"
    2. @interface class name (category name)
    3. Declaration of the new method
    4. @end


The categories are implemented as follows:

[CPP]View Plaincopy
    1. #import "class name Category name. h"
    2. @implementation class name (category name)
    3. New Method implementation
    4. @end


This is very similar to the definition of a class, except that the category has no parent class , and that there is a category name in parentheses. Names can be taken casually.

For example: if we want to add a method to the NSString to determine whether it is a URL, then you can do this:

[CPP]View Plaincopy
    1. #import ...
    2. @interface NSString (Utilities)
    3. -(BOOL) Isurl;
    4. @end


Category implementations:

[CPP]View Plaincopy
    1. #import "NSStringUtilities.h"
    2. @implementation NSString (Utilities)
    3. -(BOOL) isurl{
    4. if ([Self hasprefix:@"/http"])
    5. return YES;
    6. Else
    7. return NO;
    8. }
    9. @end


How to use:

[CPP]View Plaincopy
  1. nsstring* string1 = @"http://www.csdn.net";
  2. nsstring* string2 = @"Pixar";
  3. if ([string1 Isurl])
  4. NSLog (@"string1 is a URL");
  5. Else
  6. NSLog (@"string1 is not a URL");
  7. if ([string2 Isurl])
  8. NSLog (@"string2 is a URL");
  9. Else
  10. NSLog (@"string2 is not a URL");



Objective-c Category (categories)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.