Objective-C category (category)

Source: Internet
Author: User

Category is one of the most common functions in objective-C.

Category can add methods for existing classes without adding a subclass.

The standard syntax format of the category interface is as follows:

 
# Import "class name. H" @ Interface Class Name (Class Name) // Declaration of the new method @ end

Categories are implemented as follows:

 
# Import "Class Name class name. H" @ implementation class name (Class Name) // new method implementation @ end

This is very similar to the class definition. The difference is that category does not have a parent class.And there is a category name in the brackets. The name can be retrieved at will.

For example, if we want to add a method on nsstring to determine whether it is a URL, we can do this:

 
# Import... @ Interface nsstring (utilities)-(bool) isurl; @ end

CATEGORY implementation:

 
# Import "nsstringutilities. H "@ implementation nsstring (utilities)-(bool) isurl {If ([self hasprefix: @" http: // "]) return yes; else return no;} @ end

Usage:

Nsstring * string1 = @ "http://www.csdn.net"; nsstring * string2 = @ "Pixar"; if ([string1 isurl]) nslog (@ "string1 is a URL "); else nslog (@ "string1 is not a URL"); If ([string2 isurl]) nslog (@ "string2 is a URL "); else nslog (@ "string2 is not a URL ");

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.