Objective-c category/protocol.

Source: Internet
Author: User

Chapter 12th Category

Category:

Naming method: Class name + category name.

In Xcode, you can find the Objective-c category icon in the category of the new file.

@interface section

The declaration of a category looks much like the declaration of a class:

@interface NSString (numberconvenience)

-(NSNumber *) Lengthasnumber;

@end

In parentheses (numberconverience) is called the category name, and it is added to the NSString class. The whole sentence can be understood as: We have added a category named Numberconverience to the NSString class.

You can add attributes to a category, but you cannot add an instance variable, and the property must be of type @dynamic (dynamic), and the advantage of adding properties is that you can access the setter and getter methods through a point expression.

@implementation

@implementation NSString (numberconvenience)

-(NSNumber *) lengthasnumber{

Nsuinteger length = [self length];

return ([NSNumber numberwithunsignedint:length]);

}

@end

Benefits of the Category:

3 uses: 1. Spread the class-to-implementation code across multiple different files or frameworks.

2. Create a forward reference to the private method.

3. Add an informal agreement to the object. (Informal protocol)

Categories of defects:

1. A new instance variable cannot be added to the class, and the category has no space to hold the instance variable.

2. Name collisions, that is, the methods in the category have the same names as existing methods. When a conflict occurs, the category has a higher priority. Your class method will completely replace the initial method, resulting in the initial method being unavailable.

(using a global dictionary to store the mappings between objects and the extra variables you want to associate can overcome the limitation that the class cannot increase the instance variable.) )

A special Category: Class extension.

Features: 1. No name required. 2. You can use it in multiple classes (that is, your own class) that contain your source code. 3. You can add instance variables. 4. You can change the read-only permission to read-write permission. 5. Unlimited number of creation.

@interface Things: nsobject

@property (assign) nsinteger thing1;

@property (readonly,assign ) nsinteger thing2;

-(void) resetallvalues;

@end


@interface Thing ()

{

Nsinteger Thing4;

}

@property (readwrite,assign) nsinteger thing2;

@property (assign) nsinteger thing3;

@end

There is no inherited parent class, and what we do is basically get the things class and extend it by adding private properties and methods.

A common strategy is to put categories in front of the implementation file. When accessing private methods of other classes, no warning is generated as long as the method compiler is declared in the category.

The application cannot access private variables and methods inside the class, otherwise it will not be available through the app Store.

Informal agreements and delegate categories

Classes in cocoa often have a technique called delegate, which is an object that is requested by another class to perform some work.

The run loop is a cocoa concept that keeps blocking until something happens, without executing any code. In addition to listening for network traffic, the run loop handles actions such as wait events (keystrokes or mouse clicks).

#import <Foundation/Foundation.h>

@interface Itunesfinder: NSObject <nsnetservicebrowserdelegate>

@end

After NSObject , the Nsnetservicebrowserdelegate protocol is used to tell the compiler and other objects that the class conforms to the name-Point protocol and implements its methods.

The delegate object only needs to implement the method that it has intended to invoke.

Another application of managed emphasis categories: methods that are sent to managed objects can be declared as a nsobject category.

650) this.width=650: "title=" screenshot 2015-07-24 pm 10.00.33.png "alt=" screenshot 2015-07-24 pm 10.00.33.png "src="/e/u261/themes/ Default/images/spacer.gif "class=" ynote-attachment "style=" Background:url ("/e/u261/lang/zh-cn/images/ Localimage.png ") no-repeat center;border:1px solid #ddd;"/>

Nsnetservicebrowser implementations can send one of these messages to any object, regardless of which class they actually belong to, which means that any class object can become a delegate object as long as the delegate method is implemented.

Creating a nsobject category is called creating an informal protocol. The informal protocol is just an expression, he says, "There are some ways you might want to do this, and you can use them to do the job better." ”

The Select (selector) is just the name of a method, but he uses the OC runtime to encode it in a special way to quickly execute the query.

NSObject provides a name for the Respondstoselector: Method that is used to interrogate an object to determine whether it can respond to a particular point message.

Car *car = [[Car alloc] init];

if ([Car respondstoselector:@selector(setengine:)]) {

NSLog (@ "Yo yo..");

}

This code can normally output yo yo. Because the object of the car class does respond to the Setengine: message.

To confirm that the managed object can respond to the message, Nsnetservicebrowser calls Respondstoselector: @selector (netServiceBrowser:didFindService:moreComing :)。 If the managed object is able to respond to a given message, the browser sends this message to the object. Otherwise, the browser will temporarily ignore the managed object and continue to run normally.

Selectors can be passed, can be used as parameters of a method, and can even be stored as instance variables.

The Nstimer in the foundation framework is such a class that can repeatedly send messages to an object.

This chapter summarizes:

Categories of concepts, functions. Class extension, selector.

This chapter looks easy to understand, but it's not clear how to use it. ""

Chapter 13th Agreement

Formal Agreement:

Contains a list of names for methods and properties, but unlike informal protocols, formal agreements require explicit adoption. The @interface method is to list the name of the protocol in the class's declaration. Adopting an agreement means that you are committed to implementing all the methods of the agreement. Otherwise, you will get a warning.

NSObject can often be used as the root protocol, but unlike the NSObject class, the NSObject class conforms to the NSObject protocol, which means that all objects conform to the NSObject protocol.

The ID type represents a pointer to an object of any type, which is a generic object type. You can tell any object to copy to a variable of type ID, or vice versa.

There is a method called Setobjectvalue: in the NSControl class that requires the object to pursue the Nscopying protocol:-(void) Setobjectvalue: (id<nscopying>) object;

If two protocol modifiers are added to the protocol: @optional and @required. The method between the two modifiers can be an optional implementation.

Delegate (delegation) method:

A delegate is an object that specifies another object to handle some particular design pattern.

-(ID <nsnetservicebrowserdelegate>) delegate;

-(void) Setdelegate: (ID <NSNetServiceBrowserDelegate>) delegate;

The first method returns the current delegate object (nil If none is returned), the second is used to set the delegate, and the delegate type of the parameter tells us that any object can be set as a delegate as long as the required protocol is adhered to.



Objective-c category/protocol.

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.