Category and extension in iOS

Source: Internet
Author: User

category and extension in iOS The objective-c provides the means by which we can extend class definitions : Classes, extensions, and protocols. Category: Add a new method to a known class;extension: Notifications use classes in the definition of this class to declare private methods, and instance variables ;protocol: A protocol declares a method that can be implemented by any class .
Note: These methods can only increase the method of the class, and cannot be used to increase the instance variable (except extension), to increase the class instance variable, can only be implemented indirectly by defining subclasses.
1. Class Items
1) Declaration of category
@interface nsstring (numberconvenience)
-(NSNumber *) Lengthasnumber;
@end
the declaration has 2 characteristics. First, the existing class is behind the @interface keyword, followed by a new name in parentheses. The declaration indicates that the name of the category is Numberconvenience, and that the category adds a method to the NSString class. As long as you guarantee the uniqueness of the category name, you can add any number of categories to a class.
Second, you can specify the class to which you want to add a category and the name of the category, and you can also list the methods that you added, and finally end with @end. Because the new instance variable cannot be added , unlike the class declaration, there is no instance variable part in the declaration of the category.
2) class purpose Limitations
First, you cannot add a new instance variable to the class.
Second, the easy name conflict, that is, the method in the category is the same as the existing method. When a name conflict occurs, the category has a higher priority. Your class method will completely replace the initial method, so that the initial method can no longer be used. Some programmers add a prefix to their class methods to ensure that no name collisions occur.
There are some techniques that can overcome the limitations of categories that cannot add new instance variables. For example, you can use a global dictionary to store the mappings between objects and the extra variables that you want to associate. But at this point you might want to think about whether a category is the best choice for accomplishing your current tasks.
3) class purpose effect
The cocoa category is mainly used for 3 purposes:first, the implementation of the class is dispersed into different files or different frameworks. Second, create a forward reference to the private method . (Add a new method to an existing class)third, add an informal agreement to the object. (Implementation of a delegate with a category of informal agreements) (talk about delegates (i.e. proxies), a delegate is an application of a category, the method that is sent to the delegate object, can be declared as a nsobject category, create a nsobject category to create an "informal protocol", he said "Here are some of the ways you want to implement, Of course it can be implemented without realizing ").
2. Extension
The extension of a class can be thought of as an anonymous class , and the class sometimes needs to be seen only for itself, and the private method used by the private method can be declared in an extended manner, and the method defined in the extension is implemented in the @implementation code area of the class itself.
definition Extension
@interface Myobject:nsobject
 {     
NSNumber *number;}
-(NSNumber *) number;
@end@interface MyObject (Setter)
-(void) Setnumber: (NSNumber *) Newnumber;
@end
@implementation MyObject
-(NSNumber *) number
{     
return number;
 }
-(void) Setnumber: (NSNumber *) Newnumber
{!//do something
}
@end
When a class name is not provided when the extension is defined, the method defined in the extension is considered to be an " must-implement" API in which case the compiler will report a warning if the method lacks the implementation code. The implementation of this method must appear in the @implementation code block of the class body.
3. Protocol and Proxy mode
The protocol only declares the method and does not implement it, and the object accepting the agreement is responsible for implementing it. The OC protocol is a list of methods that are declared by @protocol, requiring other classes to be implemented , equivalent to the declarations of the @interface section.
Note:
A. The method of @required modification in the protocol should be implemented when the agreement is confirmed
B. Methods that can selectively implement @optional adornments
c. Use [Object Conformstoprotocol: @protocol (Protocol)] to determine compliance with the Protocol
D. The agreement is written in the. h file that provides the Protocol class.
Application of protocol--agent
the proxy pattern is that it does not do the time itself, but rather requires others to do it.
category and extension are used for class extensions, which can extend functionality to existing classes or modify their functionality. category apps are very broad in iOS, and many of the classes that come with the system have multiple category extensions. in the general category , you can define new methods, override the original methods of the class, and add readonly properties extension can be considered an anonymous category, but this extension has a special function with respect to Category:Writable properties can be defined in extension, public readable, private writable properties (Publicly-readable, privately-writeable properties) are generally implemented as such! usage of 1.category2. Usage of extension

iOS Learning notes 06-category and extension

I. Overview

A category is a way to add a new method to an existing class .

Using Objective-c's dynamic runtime allocation mechanism, the category provides a more concise way than inheritance (inheritance) to extend the class to add new methods to existing classes without having to create subclasses of the object class. You can add methods to any already existing class, including those that do not have source code (such as some framework classes).

Ii. examples

1. Declaration Category

@interface NSString (Categorydemo)

-(nsnumber*) Lengthasnumber;

@end

2. Realization Category

@implementation NSString (Categorydemo)

-(nsnumber*) lengthasnumber{

Nsuinteger length = [self length];

return ([Nsnumbernumberwithunsignedint:length]);

}

@end

3. Call:

Nsmutabledictionary *dic =[nsmutabledictionarydictionary];

[Dicsetobject: [@ "Hello" lengthasnumber]forkey:@ "Hello"];

[dic setobject: [@ "world!" Lengthasnumber] Forkey: @ "World"];

NSLog (@ "%@", DIC);

4. Printing results:

2012-07-27 17:43:32.993categorydemo[2193:f803] {

Hello = 5;

World = 6;

}

III. Limitations of the category

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.

Iv. Role of the category

There are 3 main functions of the category :

(1) The implementation of the class can be dispersed across multiple files or different frameworks for easy code management. You can also provide extensions to the framework (no source code, no modification).

(2) Create a forward reference to a private method : If a method in another class is not implemented, the compiler will error when you access the private method of another class, then use the category, declare these methods in the category (without providing a method implementation), and the compiler will no longer generate a warning

(3) Adding informal Co -negotiation to an object: creating a nsobject category is called " creating an informal protocol ," because it can be used as a delegate object for any class .

Iv. Expansion of extension

The following are examples of syntax for extension and category:

Extension

@interface MyObject () {

int iextension;

}

-(void) If the mainimplementation of the testinextension;//class is not implemented, there is a compile warning.

@end

Category

@interface MyObject (Categorydemo) {

int icategory; Error:ivarsmay not being placed in categories

}

-(void) testincategory;//does not force a requirement to be implemented in the class's Mainimplementation

@end

Implementation

@implementation MyObject

//

-(void) testinextension{

//

//}

//

-(void) testincategory{

//

//}

@end

The main differences between them are:

1, formally, extension is anonymous category.

2, extension in the declaration of the method needs to be implemented in Mainimplementation, category is not mandatory requirements.

3, extension can add attributes (variables), category cannot be.

Category and extension in iOS

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.