Summary of categories (Extended categories) in ios

Source: Internet
Author: User

Summary of categories (Extended categories) in ios

 

 

Category

Category is a way to add a new method to an existing class.
Using the dynamic runtime allocation mechanism of Objective-C, you can add new methods to existing classes. This method of adding new methods to existing classes is called category catagory, it can add new methods for any class, including those without source code.
Category allows you to do the same without creating a subclass of the object class.
I. Create a category
1. Declared category
The Declaration category is similar to the Declaration class.
@ Interface NSString (NumberConvenience)
-(NSNumber *) lengthAsNumber;
@ End // NumberConvenience
This statement has two features:
(1) The existing class is located behind the @ interface keyword, followed by the class name in parentheses. The category name is NumberConvenience, and this category will be added to the NSString class. In other words, "we add a class named NumberConvenience to the NSString class ."
Categories with the same name are unique, but you can add any number of different names.
(2) You can execute the class and category name you want to add to it, and list the added methods.
You cannot add new instance variables. Category life does not contain instance variables.
2. Implementation category
@ Implementation NSString (NumberConvenience)
-(NSNumber *) lengthAsNumber
{
Unsigned int length = [self length];
Return ([NSNumber numberWithUnsignedInt: length]);
} // LengthAsNumber
@ End // NumberConvenience
The implementation part also includes the implementation code of the class name, class name, and new method.
3. Category limitations
There are two limitations:
(1) You cannot add new instance variables to the class. The class does not have a location to accommodate instance variables.
(2) name conflict, that is, when the method in the category conflicts with the original class method name, the category has a higher priority. The category method will completely replace the initial method so that the initial method cannot be used.
The limitations of being unable to add instance variables can be solved using dictionary objects.
4. Role of category
Category has three main functions:
(1) Distribute the implementation of classes to multiple different files or different frameworks.
(2) Before creating a private MethodForward.
(3) add informal protocols to objects.

II. Implementation Using Scattered categories
We can put the class interface into the header file to put the class implementation into the. m file.
However, you cannot distribute @ implementation to multiple. m files. You can use categories to complete this task.
Classes can be used to organize the methods of a class into different logical groups, making it easier for programmers to read header files.
Example code:
The header file CatagoryThing. h contains the class declaration and some classes. Import it to the Foundation framework and declare it with three integer variables.
# Import
@ Interface CategoryThing: NSObject {
Int thing1;
Int thing2;
Int thing3;
}
@ End // CategoryThing
The class declaration is followed by three categories, each of which has an accessor with an instance variable, which disperses these implementations into different files.
@ Interface CategoryThing (Thing1)
-(Void) setThing1: (int) thing1;
-(Int) thing1;
@ End // CategoryThing (Thing1)

@ Interface CategoryThing (Thing2)
-(Void) setThing2: (int) thing2;
-(Int) thing2;
@ End // CategoryThing (Thing2)

@ Interface CategoryThing (Thing3)
-(Void) setThing3: (int) thing3;
-(Int) thing3;
@ End // CategoryThing (Thing3)

Class can access the instance variables of its inherited classes. The class method has the highest priority.
Categories can be distributed to different files or even frameworks.

3. Create a forward reference using category
If methods in other classes are not implemented, the compiler reports an error when you access private methods of other classes.
In this case, the class is used to declare these methods in the class (the method implementation is not required), and the compiler will not generate a warning.

Iv. Informal agreements and delegation types
Classes in Cocoa often use a technology called delegate.
A delegate is an object that requires the delegate object to perform some of its operations.
(Do not understand, learn in practice)
# Import # Import ITunesFinder. h int main (int argc, c ***** t char * argv []) {ngutoreleasepool * pool; pool = [[ngutoreleasepool alloc] init]; NSNetServiceBrowser * browser; browser = [[NSNetServiceBrowseralloc] init]; ITunesFinder * finder; finder = [[ITunesFinder alloc] init]; // because the finder is created by the alloc method, it must be released when this object is not applicable.
[Browser setDelegate: finder]; // inform browser to use finder as the delegate object [browser searchForServicesOfType: @ _ daap. _ tcp // inform the browser object to use the TCP protocol to search for DAAP-type service inDomain: @ local.]; // indicates that only the local NSLog (@ begun browsing) is searched; // indicates that the following run loop has started [[[nsunloop currentRunLoop] run]; // The run loop is a Cocoa structure, he does not perform any processing, and waits for the user's operation [browser release]; // The run method will remain running without returning, therefore, the code containing this row will not be run [finder release]; [pool release]; return (0);} // main

The class for creating an NSObject is called "Create Informal agreementBecause it can be used as the delegate object of any class

Response Selector
The selector is just a method name, but it is encoded in a special way during the Objective-C runtime to quickly execute the query
You can use @ selector () to pre-compile the specified selector. The method name is in parentheses.
For example, the setEngine of the previous Car class: the selector of the method is @ selector (setEngine :)
The setTire: atIndex; Method selector of the Car class is as follows: @ selector (setTire: atIndex ;)

NSObject provides a method named respondsToSelector that asks an object to determine whether it can respond to a specific message.
Example code:
Car * car = [[Car alloc] init];
If ([carrespondsToSelector: @ selector (setEngine :)]) {
NSLog (@ hihi );

}
Other selector applications
The selector can be passed, used as a method parameter, or even stored as an instance variable.

Summary
Categories provide a means to add new methods to existing classes, even if the source code of these classes is not available
Categories can distribute object implementations to multiple different source files or even multiple different frameworks.
Informal protocols can be declared using categories. Informal protocols are a category of NSObject, which lists the methods that an object can respond.
Informal protocols are used for delegation. Delegation is a technology that allows you to easily Customize Object behavior.




Category Is a way to add a new method to an existing class.

@ Interface NSString (NumberConvenience)
-(NSNumber *) lengthAsNumber;
@ End
(1) Add a class named NumberConveniencede to the NSString class. The class name has UniquenessYou can add Any number.
(2) You can specify the class (NSString) to which you want to add a category and the name of the category (NumberConvenience). You can also List the added methodsEnd with @ end; Category Declaration Instance variables cannot exist..
Implementation category
@ Implementation NSString (NumberConvenience)
-(NSNmuber *) lengthAsNumber {
Unsigned int length = [self length]; // obtain the string length.
Return ([NSNumber numberWithUnsignedInt: length]);
}
@ End
# Import
# Import CategoryThing. h
// Category:
// (1) implement classification in multiple different files or different frameworks
// (2) create a forward reference to a private Method
// (3) add informal protocols to objects
// Category limitations:
// (1) unable to add new instance variables
// (2) Name Conflict. If the category is the same as the existing method, the category has a higher priority. Solution: Add a prefix to the category method name.
@ Interface NSString (NumberConvenience)
-(NSNumber *) lengthAsNumber;
@ End
@ Implementation NSString (NumberConvenience)
-(NSNumber *) lengthAsNumber
{
Unsigned int length = [self length];
Return ([NSNumber numberWithUnsignedInt: length]);
}
@ End
Int main (int argc, c ***** t char * argv []) {
// All NSNumber class objects created in the applicable category will be destroyed in the Auto Release pool, and the variable dictionary will be destroyed here.
NSAID utoreleasepool * pool = [[NSAID utoreleasepool alloc] init];
// Insert code here...

NSMutableDictionary * dict;
Dict = [NSMutableDictionary dictionary];

// Use the key @ "hello" to add the integer 5 to the dictionary as follows:
[Dict setObject: [@ hello lengthAsNumber] forKey: @ hello];

[Dict setObject: [@ iLikeFish lengthAsNumber] forKey: @ iLikeFish];

[Dict setObject: [@ Once upon a time lengthAsNumber] forKey: @ Once upon a time];

NSLog (@%@, dict );

CategoryThing * thing;
Thing = [[CategoryThing alloc] init];

[Thing setThing1: 5];
[Thing setThing2: 23];
[Thing setThing3: 42];

NSLog (@ Thing are % @!, Thing );

[Thing release];

[Pool drain];
Return 0;
}
//
// CategoryThing. h
// S12_leibie
//
// Created by cwity on 11-5-17.
// Copy 2011 _ MyCompanyName _. All rights reserved.
//
# Import
@ Interface CategoryThing: NSObject {
Int thing1;
Int thing2;
Int thing3;
}
@ End
@ Interface CategoryThing (Thing1)
-(Void) setThing1 :( int) thing1;
-(Int) thing1;
@ End
@ Interface CategoryThing (Thing2)
-(Void) setThing2 :( int) thing2;
-(Int) thing2;
@ End
@ Interface CategoryThing (Thing3)
-(Void) setThing3 :( int) thing3;
-(Int) thing3;
@ End
//
// CategoryThing. m
// S12_leibie
//
// Created by cwity on 11-5-17.
// Copy 2011 _ MyCompanyName _. All rights reserved.
//
# Import CategoryThing. h
@ Implementation CategoryThing
-(NSString *) description
{
NSString * desc;
Desc = [NSString stringWithFormat: @ % d,
Thing1, thing2, thing3];

Return (desc );
}
@ End
//
// Thing1.m
// S12_leibie
//
// Created by cwity on 11-5-17.
// Copy 2011 _ MyCompanyName _. All rights reserved.
//
# Import CategoryThing. h
@ Implementation CategoryThing (Thing1)
-(Void) setThing1 :( int) t1
{
Thing1 = t1;
}
-(Int) thing1
{
Return (thing1 );
}
@ End
//
// Thing2.m
// S12_leibie
//
// Created by cwity on 11-5-17.
// Copy 2011 _ MyCompanyName _. All rights reserved.
//
# Import CategoryThing. h
@ Implementation CategoryThing (Thing2)
-(Void) setThing2 :( int) t2
{
Thing2 = t2;
}
-(Int) thing2
{
Return (thing2 );
}
//
// Thing3.m
// S12_leibie
//
// Created by cwity on 11-5-17.
// Copy 2011 _ MyCompanyName _. All rights reserved.
//
# ImportCategoryThing. h
@ Implementation CategoryThing (Thing3)
-(Void) setThing3 :( int) t3
{
Thing3 = t3;
}
-(Int) thing3
{
Return (thing3 );
}
@ End


Summary of category (Extended class) Topics in objective-c When to use category?
(1) only new methods can be added for a category. New instance variables cannot be added. (2) If the category name conflicts with the method in the original class, the category will overwrite the original method, because the category has a higher priority.
It should be noted that Objective-c only supports single inheritance. To implement multi-inheritance, it can be implemented through categories and protocols.

In addition, you should pay special attention to the fact that a class action must be extended rather than adding new instance variables to the class interface as you did during inheritance.
The category name is arbitrary.


CreateCategory
Category Is a way to add a new method to an existing class. CategoryThere are two limitations. First, you cannot add new instance variables to the class. CategoryThere is no location to accommodate instance variables. Second, name conflict, that is CategoryThe method in is the same as the existing method. When a name conflict occurs, CategoryHas a higher priority. Your CategoryThe method will completely replace the initial method, so that the initial method cannot be used. Some programmers CategoryAdd a prefix to the method name to ensure that no name conflict occurs. Some technologies can be overcome. CategoryThe limitations of new instance variables cannot be added. For example, you can use a global dictionary to store mappings between objects and the additional variables you want to associate. But at this time, you may need to seriously consider, CategoryWhether it is the best choice to complete the current task. Class Other FunctionIn Cocoa CategoryIt is mainly used for three purposes: to distribute the implementation of classes to multiple different files or different frameworks, create forward references to private methods, and add informal protocols to objects. If you do not understand the meaning of the informal protocol, do not worry. We will discuss this concept briefly later.



Objective-C class inheritance and method Overloading
This time, we will explain how to inherit classes and overload methods in Objective-C. According to the Convention, we should first give a small example of heavy load, and explain it based on the example.
# Import
@ Interface ClassA: NSObject // The ClassA type inherits the NSObject type
{
Int x; // declare a variable Member
}
-(Void) initVar; // declare the initialization method
@ End
@ Implementation ClassA // define ClassA
-(Void) initVar // defines the initialization method
{
X = 100;
}
@ End

@ Interface ClassB: ClassA // The ClassB type inherits the ClassA type.
-(Void) initVar; // declare the initialization method. This method reloads the method with the same name in ClassA.
-(Void) printVar; // declare the printing VARIABLE METHOD
@ End
@ Implementation ClassB // defines ClassB
-(Void) initVar // defines the initialization method
{
X = 200;
}
-(Void) printVar // defines the printing VARIABLE METHOD
{
NSLog (@ x = % I, x );
}

Int main (int argc, char * argv [])
{
NSAID utoreleasepool * pool = [[NSAID utoreleasepool alloc] init];
ClassB * B = [[ClassB alloc] init]; // defines a ClassB-type instance.
[B initVar]; // call the initVar method of object B.
[B printVar]; // call the printVar method of object B.
[B release]; // release the memory space occupied by object B
[Pool drain];
Return 0;
}
-------------------------------------------------------------------------------
Output:
X = 200;
-------------------------------------------------------------------------------

After reading the small example above, I immediately understood that the inheritance of Objective-C is very similar to that of C ++, and the difference is very small, when declaring the type, add a code statement. For example, if the ClassB type inherits the ClassA type, write @ interface ClassB: ClassA when defining the interface file to complete the inheritance. By the way, Objective-C cannot directly carry out multiple inheritance and must support protocols (essentially similar to interfaces in C # language.The specific content of the Protocol will be introduced later with the classification concept) to implement multi-inheritance.
Method overloading in Objective-C is also very simple. As long as the method name in the subclass is the same as the method name of the parent class, the method with the same name of the parent class can be automatically overloaded without adding any keywords.




Objective-C learning notes --- categories (methods for implementing multiple inheritance))
? A class is an existing class that adds new features.
? To add a new method to an existing class, you can use the object of the existing class to call the added method without inheriting the existing class.
? Categories can distribute the implementation of classes in multiple files.
? No variable exists in the category, and the class does not contain the variable location.
? If the method in the class is the same as the method name in the class, this will cause a conflict, and the class method will completely replace the class method.
? Different classes of the same class declare the same method, which will lead to instability, and which method will be called is uncertain.

CATEGORY statement:
# Import ClassName. h
@ Interface ClassName (CategoryName)
Method Declaration
@ End
CATEGORY implementation:
# Import ClassName + CategoryName. h "// declare the file
@ Implementation ClassName (CategoryName)
Method implementation
@ End
Instance:
FractionMath. h
# Import Fraction. h
@ Interface Fraction (Math)
-(Fraction *) add: (Fraction *) f;
-(Fraction *) mul: (Fraction *) f;
-(Fraction *) div: (Fraction *) f;
-(Fraction *) sub: (Fraction *) f;
@ End
FractionMath. m
# Import FractionMath. h
@ Implementation Fraction (Math)
-(Fraction *) add: (Fraction *) f {
Return [[Fraction alloc] initWithNumerator: numerator * [f denominator] + denominator *
[F numerator] denominator: denominator * [f denominator];
}
-(Fraction *) mul: (Fraction *) f {
Return [[Fraction alloc] initWithNumerator: numerator * [f numerator]
Denominator: denominator * [f denominator];
}
-(Fraction *) div: (Fraction *) f {
Return [[Fraction alloc] initWithNumerator: numerator * [f denominator]
Denominator: denominator * [f numerator];
}
-(Fraction *) sub: (Fraction *) f {
Return [[Fraction alloc] initWithNumerator: numerator * [f denominator]-denominator * [f numerator]
Denominator: denominator * [f denominator];
}
@ End
Main. m
# Import
# Import Fraction. h
# Import FractionMath. h
Int main (int argc, c ***** t char * argv []) {
// Create a new instance
Fraction * frac1 = [[Fraction alloc] initWithNumerator: 1 denominator: 3];
Fraction * frac2 = [[Fraction alloc] initWithNumerator: 2 denominator: 5];
Fraction * frac3 = [frac1 mul: frac2];
[Frac1 print];
Printf (*);
[Frac2 print];
Printf (= );
[Frac3 print];
Printf (/n );
// Free memory
[Frac1 release];
[Frac2 release];
[Frac3 release];
Return 0;
}



Category (also called class extension)
@ Interface Class Name (category name)// The category name can be retrieved at will
For example, in the. m file. @ Interface TEST_DRAW_APPViewController (ViewHandlingMethods) // This is a category, also called class extension.
Category: Add new behaviors for existing classes.
Subclass is a method, but it does not have the ability to renew in the face of class clusters and toolkit or class libraries.
CATEGORY solves this problem.
Create category: category is a method that provides new methods for existing classes.
Categories and extensions
Category allows you to extend the functions of a class even without the class source code and add methods to it.
The main function is to reuse the same method in a class without inheritance.
. Provides class extension for the Framework (without the source code, it cannot be modified ).
2. If you do not want to generate a new subclass, such as the NSArray extension.
3. To facilitate project management, you can share a source code in multiple places or perform method version management, collaborative development by multiple people, and replace the public version with the local version.
It is not recommended to overwrite the methods in the class in category, because the methods in the category cannot call the superClass method (because there is no metadata support)
The category method cannot overwrite other category methods of the same class. Due to improper prediction of their loading priorities, errors may occur during compilation.
Overwrite the category method of the class library to change the behavior of the entire class library. Therefore, the classes that call those methods do not know that the implementation of the methods has changed.
Warning:
Although category is not limited to any class, it is not recommended to write a category for rootClass. The reason is that the impact is large, and other developers will have problems if they do not pay attention to it.
In addition, class objects may also call these methods. Even when calling, the self pointer is not an instance but the class object itself.
Category
Classes can be implemented in different files.



In Objective-C 2.0, the Category Syntax provides a more concise way to extend the class than the inheritance method. We can add methods for any existing class.

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.