Use of category in objective-C

Source: Internet
Author: User

1. Basic concepts of category

Encapsulation is an object-oriented feature, and OC is no exception. However, sometimes we encounter a situation where we encapsulate a class and don't want to change it any more, however, we need to add a method to the class. At this time, we don't have to modify it in that class or define another subclass. We only need to add a category.

(1) A method defined in a category will become part of the original class, which is no different from calling other methods.

(2) by defining a category method for the parent class, its subclass also inherits these methods.

CATEGORY applications: (1) extension of existing classes (2) Replacement of subclasses (3) classification of methods in Classes

CATEGORY limitations:

You cannot add new instance variables to a category. The category does not have a location to accommodate instance variables. To add instance variables to a category, you can only define sub-classes.

If the method of the existing class is covered in the category, this will lead to the break of the Super message. Because the method in the category has a higher priority, generally do not overwrite the method of the existing class.

Category definition,

Naming rules for a class: Class Name (extension method name)

The category does not inherit the parent class. You only need a bracket to indicate the purpose of the class.

# Import <Foundation/Foundation. h> @ interface nsstring (mycompare)-(void) test; @ end

 
# Import "nsstring + mycompare. H" @ implementation nsstring (mycompare)-(void) test {}@ end

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.