Category in the Objective-c

Source: Internet
Author: User
Tags types of extensions

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

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.