OBJECTIVE-C Diary-Categories Category

Source: Internet
Author: User

Categories Category1, overview

Add new methods to existing classes, and the objective-c term for these new methods is "category".

2, Usage

A, Declaration category

@interface NSString (numberconvenience)

-(number *) Lengthasnumber;

@end//numberconvenience

The name of the class here is called Numberconvenience, and the new class method is Lengthasnumber.

B, Implementation category

@implementation NSString (numberconvenience)

-(NSNumber *) lengthasnumber

{

unsigned int length= [self length];

return ([NSNumber numberwithunsignedint:length]);

}//lengthasnumber

@end//numberconvenience

C, use of categories

As shown below, according to the category defined above: Numberconvenience, all NSString objects can respond Lengthasnumber

Numutabledictionary *dict;

Dict = [Nsmutabledictionary dictionary];

[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);

The above code places the "Hello" "Ilikefish" "Once upon A Time" three strings with their corresponding lengths in the variable dictionary dict.

D, the inadequacy and role of the category

Categories have the following disadvantages: one is that you cannot add instance variables to a category, and the other is that there may be a duplicate name for the method of the class and the existing method, and the category has a higher priority when there is a duplicate name.

The functions of the categories are:

The first is to scatter the implementation of the class into multiple different files or multiple different frameworks.

Explanation: In general, we can put the interface of the class into the header file (. h), place the implementation in the implementation file (. m), but not the @implementation into multiple. m files, but the categories can.

The following code explains the effect of this article.

NSWindows.h

@interface Nswindow:nsresponder

@interface Nswindow (Nskeyboardui)

@interface Nswindow (Nstoolbarsupport)

@interface Nswindow (Nsdrag)

@interface Nswindow (nscarbonextensions)

@interface NSObject (nswindowdelegate)

The above is the system comes with the Nswidows

The following code is a complete description of the decentralized implementation of the classification method

. h file

#import <Foundation/Foundation.h>

@interface categorything:nsobject{

int thing1;

int thing2;

int thing3;

}

@end//categorything

After declaring the instance variable, you continue to declare the category, which is different from the normal class: The normal class declares all methods in the interface, and the categories declare each category's methods separately. As follows:

@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)

then, will interface Categorything (THING1), Interface categorything (Thing2), Interface categorything (THING3) Implemented separately in THING1.M,THING2.M and THING3.M, as follows:

The thing1.m contains the implementation of the Thing1 class:

#import "CategoryThing.h"

@implementation categorything (THING1)

-(void) setThing1: (int) t1

{

THING1=T1;

}//setthing1

-(int) thing1

{

return (THING1);

}//thing1

@end//categorything

The THING2.M contains the implementation of the Thing2 class:

#import "CategoryThing.h"

@implementation categorything (Thing2)

-(void) SetThing2: (int) t2

{

Thing2=t2;

}//setthing2

-(int) thing2

{

return (THING2);

}//thing2

@end

The second is a forward reference to the private method.

When we want to create a method of privatization of a class, it seems impossible in OB, but we can use categories to implement it.

The following can be true in OB: We do not declare a method in the interface, but we implement the method in the implementation file, and the method can be called, the disadvantage is that the compiler will error.

At this point, we can use the category, define the class as a category, then, where we can not be declared in the interface, and implemented in the implementation and callable, this method is called by the developer as a private method in the OB. The implementation process is as follows:

@interface Car (Privatemethods)

-(void) movetirefromposition: (int) pos1

Toposition: (int) Pos2;

@end//privatemethods

Here is the method implementation details

@implementation Car (Privatemethods)

-(void) movetirefromposition: (int) pos1

Toposition: (int) Pos2

{

//..... Theimplementation of Methods

}//movetirefromposition:toposition

-(void) rotatetires{

//..... The implementation of methods

}//rotatetires

The third is to add an informal protocol (informal protocol) to the object.

First of all, on the delegation, after reading the Apple Developer documentation, my understanding of the delegation is that it is a way to isolate some of the cured message response operations from their original actions. For example, the original closed window is an already solidified operation does not require us to implement its specific details, but when we need to close the window to do something else, such as saving data, close connection, etc., we need an interface to help.

It is a technique commonly used by classes in cocoa, where a delegate is an object, and an object of another class requires the delegate object to perform some of its operations. A delegate is a design pattern that has a reference to the delegate (the Delegating object), which can send a message to the delegate, and the delegate (the delegate) responds to certain actions based on the message. and feedback the results of some actions by returning values.

In the Apple developer documentation, this explains the delegate:

A delegate is an object that, when another object encounters an event, represents or collaborates with another object to accomplish something. Typically, the Deletaging object is typically a response object (Responsder object) inherited from Nsresponder to respond to user events. The delegate (the delegate) is an object that authorizes the control of the user interface, or at the very least interprets the event in a particular application.

For example, some window objects have been designed to be used primarily to respond to events such as zooming out of windows, closing windows, minimizing windows, and this closed design will certainly not know for sure whether these events will have tens of thousands of other effects, such as closing a window, window objects have long been designed how to close windows, etc. But will the action of closing the window affect the preservation of the data? Interruption of network connection? Wait for other states to cause an impact, the window object is completely unknown. The presence of a delegate bridges the bridge between our custom objects and ready-made objects.

Typically, the delegating object has a outlet or property, usually named delegate, and if it is outlet, it also contains a method for accessing outlet. Usually there is a declaration of one or more methods, usually not implemented, constituting an informal agreement or a formal agreement. In the case of a formal agreement, the method is declared optional, and usually the formal agreement is used more generally. As shown, an example of a delegate's diagram:

The methods in the protocol are usually marked with important events that need to be handled by the agent. The delegate object (the delegating objects) passes these events or upcoming events to the delegate (delegate object) to request that the delegate object be reflected. For example, when a user clicks the Close button of a window, the Window object will improve a window to close the message to the agent, which gives the proxy object an opportunity to decide what needs to be done when the window is closed, as shown in the Window object, which also needs to save the data.

But the delegate object delegating objects only sends the message that the delegate delegate defines. This allows the Respondstoselector method of the NSObject object to be called.

Usually the form of the delegate method is more convenient, usually there is no ui,ns prefix, and the name often contains verbs, such as open, or temporal adverbs, such as Will,has. Some delegate methods with return values and no return values are shown in the heart:

-(BOOL) Application: (NSApplication *                        Sender 
 openFile: (NSString *) filename; NSApplication 
-(BOOL) Application: (UIApplication *) Application 
/td>
 Handleopenurl: (nsurl *) URL; Uiapplicationdelegate 
-(Uitablerowindexset *) TableView: (Nstableview       *) TableView 
 willselectrows: (Uitablerowindexset *) selection; Uitableviewdelegate 
-(Nsrect) Windowwillusestandardframe: (Nswindow *)                        Window 
 defaultframe: (nsrect) Newframe; Nswindow 

These methods can interrupt the events that occur next, or change a suggested value. You can even define an event that occurs next, such as when an agent delegate implements the Applicationshouldterminate method, it can return a Nsterminatelater object.

Here are some delegate methods that do not have return values, they are purely messages.

-(void) TableView: (nstableview*) TableView
    Mousedowninheaderoftablecolumn: (Nstablecolumn *) TableColumn;      Nstableview
-(void) Windowdidmove: (nsnotification *) notification;                 Nswindow
-(void) Application: (UIApplication *) application
    Willchangestatusbarframe: (CGRect) newstatusbarframe;               UIApplication
-(void) Applicationwillbecomeactive: (nsnotification *) notification;   NSApplication

But let's take a look at each of the two and fourth methods, where the arguments are nsnotifications objects, which means that when these methods are called, some specific messages (particular notification) are passed to these methods, such as windowDidMove:方法就与windows的通知 NSWindowDidMoveNotification. There is a connection.

How do I use a delegate?

Use of informal agreements

Use the formal protocol, as shown in the example below:

//

Main.m

Delegationtest

//

Created by Dbseti on 16/7/21.

COPYRIGHT©2016 year Dbseti. All rights reserved.

//

#import <Foundation/Foundation.h>

@protocol Secprotocol <NSObject>

-(void) payoff;

-(void) Tel;

@end

@interface secret:nsobject<secprotocol>

@end

@implementation Secret

-(ID) init{

if (Self=[super init]) {

}

return self;

}

-(void) payoff{

NSLog (@ "secret payoff");

}

-(void) tel{

NSLog (@ "Secret tel");

}

@end

@interface Boss:nsobject

@property (nonatomic,retain) ID <SecProtocol> delegate;

-(void) Manager;

-(void) teach;

@end

@implementation Boss

@synthesize delegate=_delegate;

-(ID) init{

if (Self=[super init]) {

}

return self;

}

-(void) manager{

NSLog (@ "Boss manage");

}

-(void) teach{

NSLog (@ "Boss teach");

}

-(void) payoff{

[_delegate payoff];

}

-(void) tel{

[_delegate Tel];

}

@end

int main (int argc, const char * argv[]) {

@autoreleasepool {

Secret *sec=[[secret Alloc]init];

Boss *b=[[boss Alloc]init];

b.delegate=sec;//This step is critical, it assigns the SEC to the agent of B delegate, actually it is the member of B to perform this operation

[B teach];

[B manager];

[B payoff];

[B Tel];

Insert code here ...

NSLog (@ "Hello, world!");

}

return 0;

}

Their logical relationship is shown in slices.

No protocols are used.

Back condition: There is object A and object B, object A has a method p, object B has no method p, but it wants to use method p, which let a go to invoke the P method, this is the most basic delegate. (In fact, as I understand it, this is simply called method p in the A object) there are not too many new concepts and methods.

@interface A:nsobject

-(void) p;

@end

@implementation A

-(void) p

{

NSLog (@ "I am A ' s method P");

}

@end

@interface B:nsobject

{

A * delegate;

}

@property (Nocopy,retain) A * delegate;

@end

@implementation B

@synthesize a*delegate;

@end

void Main () {

B * B=[[b alloc] init];

A * A=[[a alloc] init];

B.delegate=a;

[B.delegate P];

}

There is another way, as shown in the Class A contains an object of Class B and a print method, when the Class A is implemented, there is one more method viewdidload and an attribute Delegate;b class contains a type ID delegate

@interface a:nsobject{

B *b;

}

-(void) print;

@end

@implementation A

@synthesize delegate;

-(void) viewdidload{

B=[[b Alloc]init];

b.delegate=self;

}

-(void) print{

NSLog (@ "Print was called");

}

@interface b:nsobject{

ID delegate;}

@property (nonmatic,retain) ID delegate;

@end

@implementation B

-(void) callprint{

[Self.delegate print];

}

@end

Objective-c Journal-category

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.