Category in objective-c
Category in oc is similar to extension in swift. It is often used to extend some methods for Int, NSString, NSArray, and other basic data type objects.
There are two main purposes: Basic Type Extension and function forward definition.
Basic Type Extension
In the following example, you can add the reverse method to NSString.
Create an NSString + ReverseString extension class. 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
Ease of use:
#import “NSString+ReverseString.h"NSString *str = @“hello world”;NSString *reverseStr = [str reverseString];
Note: In category, you can only extend methods, but not attributes.
Function forward Definition
Look at this Application Scenario: In. in the m file, test2 is called in the test1 method, but test2 is defined after test1, which will bring a warning to the function definition. we can put test2 in. this warning can be eliminated after being defined in the H file. If you do not want to do this, you can use category to implement it.
In the. m file, use category to define test2, which is to privatize test2 (external access is not allowed) without leading to Function Definition Issues.
@interface Foo (Private)- (void)test2;@end@implementation xxx@end
The specific code is not pasted.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.