Category Object-c (category)

Source: Internet
Author: User

A class is one of the most useful features in object-c. Essentially, the class allows you to add some methods to an existing class without having to subclass the class, or you need to know the implementation details of the class.

This is especially useful because you can add methods to an built-in object. When you want to add a method to an instance of all NSString types in your application, you only need to add a class, without having to add the method by defining a subclass.

For example, I want to add a method to NSString to determine if it is a URL, like this:

#import <Cocoa/Cocoa.h>

@interface NSString (Utilities)

-(BOOL) Isurl;

@end

This is much like a declaration of a class. The difference is that the parent class is not listed later, and the class purpose name is written in parentheses. The name of the class object can be taken casually, but it is better to express what you have to do with the methods contained in the class.

The following is an implementation. Remember, this is not a good way to check URLs. We're just trying to make sense of the concept of class purpose.

#import "Nsstring-utilities.h"

@implementation NSString (Utilities)

-(BOOL) Isurl

{

if ([Self hasprefix:@ "//"])//string preceded by the string

{

return YES;

}

else{

return NO;

}

}

@end

Now that you can use this method of NSString, the following code will print "string1 is a URL" in the console;

NSString *string1 = @ "http://www.baidu.com";

NSString *string2 = @ "Baidu";

if ([string1 Isurl])

{

NSLog (@ "string1 is a URL");

}

if ([string2 Isurl])

{

NSLog (@ "string2 is a URL");

}

Unlike subclasses, you cannot add instance variables through the class. But you can override a method that already exists in the class by overriding it, and of course, be very careful when rewriting.

Remember that when you change a class from a class, this change affects all instances of this class in your application.

Category Object-c (category)

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.