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 ");