12.1 Creating categories
Categories are a way to add new methods to existing classes
Example: Get the length of the string and store it in the NSDictionary dictionary
Ways to not use categories:
NSNumber * number;
number = [NSNumber numberWithUnsignedInt: [string length]];
// ... do something with number
Ways to use categories:
Declaration of category:
@interface NSString (NumberConvenience)
-(NSNumber *) lengthAsNumber;
@end // NumberConvenience
note:
Write category name in parentheses, add to NSString
Categories cannot add instance variables, so there is no declaration section for instance variables
You can add attributes, but the attributes must be dynamic. The advantage of adding attributes is that you can access the setter and getter methods through dot expressions.
Implementation of the category:
-(NSNumber *) lengthAsNumber {
unsigned int length = [self length];
return ([NSNumber numberWithUnsignedInt: length]);
// Send lengthAsNumber to the string, return the NSNumber object of the length of the string
} // lengthAsNumber
Test file:
NSMutableDictionary * 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); // Output: "key = key content"
Advantages: As long as you enter a string and send lengthAsNumber to the string, you can immediately return the NSNumber object of the length of the string
note:
This category belongs to NSString, so any NSString object can respond to lengthAsNumber messages
Defects in category 12.11:
Cannot add new instance variables to the class
Name conflicts, when the method name of a category is the same as an existing method, the category has higher priority (to avoid using a prefix)
12.12 Category Advantages:
Spread the implementation code of a class into multiple different files or frameworks
Create forward reference to private method pair
Adding an informal protocol to an object
12.2 Class extensions
Class extension: A special category that does not require a name.
Features:
No name required
Can use it in your own class
Can add instance variables
Can change read-only permissions to read-write permissions
Unlimited number of creations
Example: Creating an Extension of the Things Class
The original Things class:
@interface Things: NSObject
@property (assign) NSInteger thing1;
@property (readonly, assign) NSInteger thign2;
Extending the Things class:
// Get the Things class and extend it by adding private properties and methods
@interface Things ()
{
NSInteger thing4; // Private
}
@property (readwrite, assign) NSInteger thing2; // Changed read and write permissions, private methods that can only be accessed in this class, only getter methods in public interfaces
@property (assign) NSInteger thign3; // private
note:
One of the characteristics of object-oriented programming is information hiding, which only needs to show the needs of the user, and others do not. We can put this category in an .m file or in a private header file.
12.3 Implementing Code with Category Decentralization
If you want to spread large (many ways) classes into multiple different .m files, you can use categories.
The NSWindow class has hundreds of methods, but uses classifications:
@interface NSWindow (NSKeyboardUI) // Keyboard
@interface NSWindow (NSToolbarSupport) // toolbar
@interface NSWindow (NSDrag) // Drag and drop function
@interface NSWindow (NSCarbonExtensions)
note:
Categories can access instance variables of their inherited classes
Not only can the implementation code of a class be distributed among multiple different source files, but also multiple different frameworks
Cocoa's designers put data functions in the Foundation framework through categories, while drawing is placed in the Appkit framework.
12.4 Creating Forward References by Category
If you call a method without the convenience of a method declaration, or if you are using a method that is not yet published in another class, then you need a category.
specific methods:
Declare the rotateTires method in the public interface of the Car class, and declare the move in the class
TireFromPosition: toPosition: method to implement rotateTires method, rotateTires method can use it.
@intreface Car (Private)
-(void) moveTireFromPosition: (int) pos1 toPosition: (int) pos2;
@end // Private
Note: Put into respective @implementation files
12.5 Informal agreements and delegation categories
Informal protocols are a category of NSObject that list the methods that an object can respond to. Informal agreement for delegation
A delegate is an object that is requested by another class to perform some work. Delegating is a technique that allows you to easily customize the behavior of laid-offs.
example:
When the user clicks on a row, before the tableView object is ready to execute, it asks if its delegate object can select this row.
12.51 ITUnesFinder project (omitted)
// New NSNetServiceBrowser object:
NSNetServiceBrowser * browser;
browser = [[NSNetServiceBrowser alloc] init];
// new ITunesFinder object
ITunesFinder * finder;
finder = [[ITunesFinder alloc] init];
// Tell net browser to use the ITunesFinder object as a proxy
[browser setDelegate: finder];
// Tell browser to search iTunes share
[browser searchForServicesOfType: @ "_ daap._tcp"
inDomain: @ "local."];
12.52 Delegations and categories
Delegate is another application of category. A NSObject category can be sent to the delegate object.
@interface NSObject (NSNetServiceBrowserDelegateMethods)
-(void) netServiceBrowserWillSearch:
(NSNetServiceBrowser *) browser;
-(void) netServiceBrowserDidStopSearch:
(NSNetServiceBrowser *) browser;
-(void) netServiceBrowser:
(NSNetServiceBrowser *) browser
didRemoveService: (NSNetService *) service
moreComing: (BOOL) moreComing;
@end
By declaring a class of NSObject, NSNetServiceBrowser can send one of these messages to any object (the object acting as a proxy)-an informal protocol
Note: For informal agreements, you can only state what you want.
12.53 Response selector
Selector: just a method name
Specify selector: @selector ();
Car class's setEngine: method selector: @selector (setEngine :)
Car class's setTire: atIndex: method's selector: @selector (setTire: atIndex :)
Ask the object if it can respond to a specific message
Car * car = [[Car alloc] init];
if ([Car respondsToSelector: @selector (setEngine :)])
{
NSLog (@ "Yes");
}
Copyright statement: This article is an original article by the blogger and may not be reproduced without the permission of the blogger.
[Study Notes—Objective-C] Chapter 12 of Objective-C-Basic Tutorial Second Edition