Summary of category categories (extension classes) in iOS

Source: Internet
Author: User

Category

A category is a way to add a new method to an existing class.
With Objective-c's dynamic run-time allocation mechanism, you can add new methods to existing classes, a way to add new methods to existing classes called Category Catagory, and he can add new methods to any class, including those that do not have source code.
Category allows you to do the same without creating subclasses of the object class
First, create a category
1. Declaration Category
The declaration category is similar to the form of declaring a class

@interface NSString (numberconvenience)
-(NSNumber *) Lengthasnumber;
@end//numberconvenience

This statement has two features:
(1)The existing class is located after the @interface keyword, followed by the name of the category in parentheses. the category name is Numberconvenience, and the category adds a method to the NSString class. In other words: "We add a category named Numberconvenience to the NSString class. "
Categories with the same name are unique, but you can add as many different name categories as you choose.
(2) You can perform the classes you want to add a category to and the name of the category, and also list the methods you added
You cannot add a new instance variable, and there is no instance variable part of the class life.
2. Realization Category
@implementation NSString (numberconvenience)
-(NSNumber *) lengthasnumber
{
unsigned int length = [self length];
return ([NSNumber numberwithunsignedint:length]);
}//lengthasnumber
@end//numberconvenience
In the implementation section also includes the class name, the category name, and the implementation code of the new method
3. Limitations of categories
There are two limitations:
(1) A new instance variable cannot be added to the class, and the class has no location to hold the instance variable.
(2) name conflict, where the category has a higher precedence when the methods in the category conflict with the original class method name. The class method will completely replace the initial method so that the initial method can no longer be used.
Limitations of the inability to add instance variables can be resolved using a Dictionary object
4, the role of the category
There are 3 main functions of the category:
(1) The implementation of the class is dispersed across several different files or multiple frameworks.
(2) Create a forward- to -use approach to the private method.
(3) Add an informal agreement to the object.

Second, the use of category dispersion to achieve
We can put the interface of the class into the header file, thus putting the implementation of the class into the. m file
However, the @implementation can not be dispersed across several different. m files, using categories to accomplish this work
By using categories, you can organize the methods of a class into different logical groupings, making it easier for programmers to read header files
Example code:
Header file CatagoryThing.h contains the declaration of the class and some categories, import the foundation framework, and then the declaration with 3 integer variables

#import <Foundation/Foundation.h>
@interface Categorything:nsobject {
int thing1;
int thing2;
int thing3;
}
@end//Categorything

class declaration is followed by 3 categories, each with an accessor for an instance variable that is scattered across 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)

The


category can access an instance variable of its inherited class, with the highest priority
category can be spread to different files, or even different frames

Iii. using categories to create forward references
if methods in other classes are not implemented, When you access the private methods of other classes, the compiler errors
when you use categories, declare them in categories (without providing a method implementation), and the compiler will no longer generate warnings

Four, informal agreements and delegate categories
classes in cocoa often use a class called Delegate ( Delegate technology The
delegate is an object, and the object of another class requires the delegate object to perform some of his actions
(not understood, learned in practice)

#import <Foundation/Foundation.h> #import "ITunesFinder.h" int main (int argc, c*****t char *argv[]) { NSAutoreleasePool *pool;pool = [[NSAutoreleasePool 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 available [browser setdelegate:finder];//tells browser to use the Finder as the delegate object [browser Searchforservicesoftype: @ "_daap._tcp"//tells browser object to use TCP protocol to search for DAAP type service indomain: @ "Local."];/ /means search only local NSLog (@ "begun browsing");//indicates that the following run loop has started [[Nsrunloop Currentrunloop] Run];//run loop is a cocoa construct, he does not perform any processing, Wait for the user's action [the browser Release];//run method will remain running without returning, so the code that contains this line will not be run [finder release]; [Pool Release];return (0);

}//Main

Creating a nsobject category is called "Creating ainformal agreements"Because it can be used as a delegate object for any class

Response Selector
The selector is just a method name, but it is encoded in a special way with the OBJECTIVE-C runtime to quickly execute a query
You can use @selector () precompilation to specify the selector, where the method name is in parentheses
For example, the setengine of the previous car class: The selector for the method is: @selector (setengine:)
The settire:atindex of the car class; The selector for the method is as follows: @selector (Settire:atindex;)

NSObject provides a method called Respondstoselector that asks the object to determine whether it can respond to a particular message
Example code:
Car *car = [[Car alloc] init];
if ([Carrespondstoselector: @selector (setengine:)]) {
NSLog (@ "Hihi");
}
Other applications for selectors
Selectors can be passed, can be used as parameters of a method, and can even be stored as instance variables

Summary
Categories provide the means to add new methods to existing classes, even without the source code for those classes
Categories can spread the implementation of objects across multiple different source files, or even multiple different frameworks
Use categories to declare informal agreements, which are a category of nsobject that can list the methods that an object can respond to
Informal protocols are used for delegates, and delegates are a technique that allows easy customization of object behavior




Categoryis a way to add a new method to an existing class.

@interface NSString (numberconvenience)
-(NSNumber *) Lengthasnumber;
@end
(1) Add a category named Numberconveniencede to the NSString class; the category name hasUniqueness, you can add a class to aany number ofThe category.
(2) You can specify the class (NSString) to which you want to add a category, and the name of the category (Numberconvenience), and you canlist the methods added, end with @end; category Declarations Sectioncannot have instance variable part
Implementation category
@implementation NSString (numberconvenience)
-(Nsnmuber *) lengthasnumber{
unsigned int length = [self length];//get string length
return ([NSNumber numberwithunsignedint:length]);

@end
#import <Foundation/Foundation.h>
#import "CategoryThing.h"


The role of the category:
(1) Dispersing category implementations into multiple different files or multiple frameworks
(2) Creating a forward reference to a private method
(3) Adding an informal agreement to an object
Limitations of the Category:
(1) Unable to add new instance variable
(2) Name conflicts, if the category and existing methods have duplicate names, the category has a higher priority, workaround, 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 objects of the NSNumber class created by our category will be destroyed in the auto-free pool, and the mutable dictionary will be destroyed here.
NSAutoreleasePool * Pool = [[NSAutoreleasePool alloc] init];
Insert code here ...

Nsmutabledictionary *dict;
Dict=[nsmutabledictionary dictionary];

Use the key @ "Hello" to add an integer value of 5 to the dictionary code 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 is%@!", Thing);

[Thing release];

[Pool drain];
return 0;
}


#import <Cocoa/Cocoa.h>
@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


#import "CategoryThing.h"
@implementation categorything
-(NSString *) description
{
NSString *desc;
desc= [NSString stringwithformat:@ "%d%d%d",
THING1,THING2,THING3];

return (DESC);
}
@end

#import "CategoryThing.h"
@implementation categorything (THING1)
-(void) setThing1: (int) t1
{
THING1=T1;
}
-(int) thing1
{
return (THING1);
}
@end

#import "CategoryThing.h"
@implementation categorything (Thing2)
-(void) SetThing2: (int) t2
{
Thing2=t2;
}
-(int) thing2
{
return (THING2);
}

#import "CategoryThing.h"
@implementation categorything (THING3)
-(void) SetThing3: (int) t3
{
THING3=T3;
}
-(int) thing3
{
return (THING3);
}
@end

Summary of category categories (extension classes) in iOS

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.