OC-objective concepts and usage, oc-category concepts

Source: Internet
Author: User

OC-objective concepts and usage, oc-category concepts

The previous article introduced the use of the @ class keyword in OC.

First, let's take a look at the scenario. If we want to expand the functions of a class, what should we do?

For object-oriented programming, we will first think of inheritance, but there are two problems with inheritance:

First, the premise of inheritance is that this class can be inherited because some classes in Java are not allowed to be inherited and are defined as final classes, the same OC Contains classes that cannot be inherited.

The second problem: this class can be inherited, but we know it is invasive, that is, I may just want to implement a function, but after inheritance, subclass will inherit all the features (attributes and methods) of the parent class, which is too costly. No


So in Java, we can implement this by means of aggregation,

For C ++, define a function class directly, and then let the target class inherit the function class, because C ++ can inherit more

Java and OC are single-inherited and do not allow many inheritance


In OC, we can also adopt aggregation processing in the way of Java, But there is a more powerful processing method in OC, that is, category. The following is an example: now we want to provide the NSString class with the validateEmail Method for email verification. The NSString class in OC cannot be inherited.

If you don't talk about it, check the Code directly:

NSString + Extension. h

//// Extension. h // 09_ClassTarget /// Created by jiangwei on 14-10-11. // Copyright (c) 2014 jiangwei. all rights reserved. // # import <Foundation/Foundation. h> // define the naming rules for the object file: class name + category name, for example, "NSString + Extension. h "@ interface NSString (Extension)-(BOOL) validateEmail; // overwrite the intValue method in NSString-(NSInteger) intValue; @ end

NSString + Extension. m

//// Extension. m // 09_ClassTarget /// Created by jiangwei on 14-10-11. // Copyright (c) 2014 jiangwei. all rights reserved. // # import "NSString + Extension. h "@ implementation NSString (Extension)-(BOOL) validateEmail {nsange range = [self rangeOfString: @" @ "]; if (range. location = NSNotFound) {return NO;} else {return YES ;}// you can see that the intValue method in NSString cannot be called here, this is different from the inheritance-(NSInteger) intValue {NSLog (@ "intValue"); return 0 ;}@ end
Here we define a category, which will be explained below:

Definition Format of category files:

Format of the Object Name:"You need to add the category name + category name"

For example, to add a category Extension to the NSString class, the file name is NSString + Extension. h and NSString + Extension. m.



CATEGORY Definition Format:

@ Interface: You need to add the category name (category name)

....

@ End

This is similar to the Class Definition Format, that is, a bracket category name is added to the end.

For example:

@ Interface NSString (Extension)

....

@ End


CATEGORY names can be retrieved at will.


See the above Code, in NSString + Extension. h

We can define the validateEmail method, and define an intValue method.

The intValue method is available in NSString itself. This is to demonstrate that if an existing method in the class is redefined in the added category, the method in the category will be overwritten, it is similar to class inheritance, but here you need to note that the super keyword cannot be used to call the intValue method of NSString. Therefore, after intValue overwrites the intValue method in the NSString class, the intValue method in the NSString class has no functions. Pay attention to this.


Let's take a look at the test code.

Main. m

//// Main. m // 09_ClassTarget /// Created by jiangwei on 14-10-11. // Copyright (c) 2014 jiangwei. all rights reserved. // # import <Foundation/Foundation. h> # import "NSString + Extension. h "// This is just to demonstrate that if you want to extend the functions of a class, you can implement it by inheritance. // However, If you implement this function by inheritance, it is a little useless, because we only need a method to determine the legitimacy of the mailbox, the inheritance is too large and there is no need to // but there will be errors here, because NSString is not allowed to inherit //, we need to use a very powerful technology here: the category/Category objective definition is similar to the tired definition, in. statement in the H file ,. the implementation method // category in the m file can overwrite the method, but the previous method will not be executed. Instead, the new method // category cannot be called to add attributes (instance variables) to the class) int main (int argc, const char * argv []) {@ autoreleasepool {NSString * s = @ "123456@qq.com"; BOOL isEmail = [s validateEmail]; if (isEmail) {NSLog (@ "valid email");} else {NSLog (@ "invalid email ");} // call the intValue method NSInteger I = [s intValue]; NSLog (@ "intValue is % I", I);} return 0 ;}
In this way, we add a mailbox Verification Method to the NSString class, And the intValue method in the category also overwrites the intValue method in the original class.


Through this example, we can see that the categories in OC are really powerful !!

In addition, a category actually has a hidden usage. It can be understood from its literal meaning as a classification function. For example, a method in a class may sometimes need to be classified (for example, printing a category, ), so the code looks elegant. Let's look at the NSArray class in the Foundation framework (this class is similar to the List in Java ):


There is also a category.


Here we also learned,A class can define multiple classes. In addition, the purpose of the class can be inherited into the subclass, that is, the method subclass in the category of the parent class can still be called using the super keyword.


Summary

This article introduces a powerful category of functions in OC, which plays a crucial role in future scalability, this function will be frequently used in the future.

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.