The category in OC is similar to the extension in Swift. It is often used to extend some methods to objects of the basic data types such as int, NSString, Nsarray, and so on.
There are two main uses: the basic type extension and the function forward definition.
Basic types of extensions
As an example, you can add a reverse method to nsstring.
The extension class for the new Nsstring+reversestring, in. h
// NSString+ReverseString.h@interface NSString (ReverseString)- (id)reverseString;@end
In the. m file, implement the ReverseString method:
//nsstring+reversestring.m @implementation NSString (reversestring ) -(id ) reversestring {Nsuinteger len = [self length]; nsmutablestring *returnstr = [nsmutablestring Stringwithcapacity:len]; while (LEN) {unichar c = [self Characteratindex:--len]; //two bytes [Returnstr appendstring:[nsstring stringwithformat:@ "%c", C]]; } return returnstr;} @end
Very simple to use:
#import “NSString+ReverseString.h"NSString *str = @“hello world”;NSString *reverseStr = [str reverseString];
Note: You can only extend the method in the category, not the properties.
function forward Definition
Look at this scenario: in the. m file, Test2 is called in the Test1 method, but test2 is defined behind Test1, which is a warning that a function forward is defined. We can eliminate this warning by placing test2 in the. h file, and if you do not want to do so, you can do so by using category.
Use category in the. m file to define TEST2, which is going to be test2 privatized (externally inaccessible) without the problem of function forward definition.
@interface Foo (Private)- (void)test2;@end@implementation xxx@end
The specific code will not be posted up.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Category in the Objective-c