Objective-C -- Category

Source: Internet
Author: User

Objective-C -- Category

Encapsulation is a feature of object-oriented, and OC is no exception, but sometimes we will encounter such a situation. For example, I encapsulate a class and don't want to change it any more, however, as the program functions increase, we need to add a small method to that class. In this case, we do not have to modify or define a subclass in that class, you only need to add a category of the class when using that method.

(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 the category method for the parent class, its subclass also inherits these methods. If a subclass adds a category method, the parent class does not have a category method of the subclass;

 

Application of category method:

(1) extend existing classes: for example, you can extend the classes in the Cocoa Touch framework. The methods you add to the categories will be inherited by the quilt classes, and there is no difference with other methods at runtime.

(2) as an alternative to subclass: you do not need to define or use a subclass. You can directly add methods to existing classes by category.

(3) classification of methods in the class: Use category to divide a large class into small pieces for separate development, so as to better update and maintain the methods in the class.

 

Limitations of the category method:

(1) You cannot add new instance variables to the category. The category has no location to accommodate instance variables. To add instance variables of a class, you can only define the subclass.

(2) If the method of the existing class is overwritten in the category, the super message is broken because the method in the category has a higher priority. Therefore, do not overwrite the methods in the existing class.

 

Class naming and usage:

Class naming rules: class name + class method, such as "NSString + Revert"

The class interface declaration is very similar to the class definition, but the class does not inherit the parent class. It only needs to carry a bracket to indicate the main purpose of the class.

 

In fact, Apple also uses the category idea when designing OC, and the most common is in the Foundation framework. As shown in NSArray:

.

 

.

 

The following code implements the Category. Create a Command Line Tools program.

[Extended custom class] (1) create a Person class and implement the following in Person. h:

 

# Import
 
  
@ Interface Person: NSObject @ property (nonatomic, strong) NSString * name;-(void) test;-(void) eat; @ end // it is possible that we define a Category in the same class. you can also create a new Category file; @ interface Person (Creation) // instance method-(id) initWithName :( NSString *) aName; @ end @ interface Person (Life)-(void) eat;-(void) sleep;-(void) play; @ end
 

(2) implement the following in Person. m:

 

 

# Import Person. h @ implementation Person-(void) test {NSLog (@ This is a method of the original class);} // will be overwritten by the method with the same name in Category;-(void) eat {NSLog (@ This is the eat of the original class);} @ end @ implementation Person (Creation)-(id) initWithName :( NSString *) aName {self = [super init]; if (self) {self. name = aName;} return self;} @ end @ implementation Person (Life) // a warning is given here when you implement the same method in the original class. However, during the call, the method with the same name in the Category will overwrite the method in the original class;-(void) eat {NSLog (@ He needs to eat);}-(void) sleep {NSLog (@ he needs to go to bed);}-(void) play {NSLog (@ he needs to play);} @ end

(3) implement the following in main. m:

 

 

# Import
 
  
# Import Person. hint main (int argc, const char * argv []) {@ autoreleasepool {Person * jack = [[Person alloc] initWithName: @ Jack]; NSLog (@ Person: % @, jack. name); [jack test]; // call the method in Category; [jack eat]; [jack sleep]; [jack play];} return 0 ;}
 

(4) the output is as follows:

 

.

 

Class provided by the extended system]

(1) we use the NSArray class as an example to add methods in NSArray. Create a new Convert category from NSArray to reverse the elements in the array. The implementation in NSArray + Convert. h is as follows:

 

# Import
 
  
@ Interface NSArray (Convert) // Add a method for NSArray; + (NSMutableArray *) arrayFromNumber :( int) number; @ end
 

(2) The implementation in NSArray + Convert. m is as follows:

 

 

# Import NSArray + Convert. h @ implementation NSArray (Convert) + (NSMutableArray *) arrayFromNumber :( int) number {NSMutableArray * numberArray = [[NSMutableArray alloc] init]; while (number) {int last = number % 10; // retrieve the last digit; number/= 10; // remove one digit; [numberArray addObject: [NSNumber numberWithInt: last];} return numberArray;} @ end

(3) implement the following in main. m:

 

 

#import 
 
  #import NSArray+Convert.hint main(int argc, const char * argv[]) {  @autoreleasepool {        NSMutableArray *numberArray = [NSArray arrayFromNumber:123];    for (NSNumber *number in numberArray) {      NSLog(@number:%@,number);    }      }  return 0;}
 

(4) the output is as follows:

 

.

 

 

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.