Objective-C classification

Source: Internet
Author: User

By classification, you can add new methods to existing classes without the need for source code. This is a bit like the Extension Method in C.

In this case, an example is provided to convert a string into a camper type and remove spaces.

Nsstring + camelcase. h

 
# Import <Foundation/Foundation. h> // nsstring indicates the name of the class to be added. The class must already exist. // Camelcase is the name of the category added for the class. // You can only add methods, but not variables. // Naming convention for header files: classname + categoryname. h @ interface nsstring (camelcase)-(nsstring *) camelcasestring; @ end

Nsstring + camelcase. m

# Import "nsstring + camelcase. H" @ implementation nsstring (camelcase)-(nsstring *) camelcasestring {// call the internal method of nsstring to obtain the hump string. // Self points to the class of the added category. Nsstring * castr = [self capitalizedstring]; // creates an array to filter out spaces and combines characters using separators. Nsarray * array = [castr componentsseparatedbycharactersinset: [nscharacterset whitespacecharacterset]; // output nsstring * output = @ ""; for (nsstring * word in array) {output = [Output stringbyappendingstring: Word];} return output ;}@ end

Main. m

#import 
  
    # import "nsstring + camelcase. H "int main (INT argc, const char * argv []) {ngutoreleasepool * Pool = [[ngutoreleasepool alloc] init]; nsstring * STR = @" My name is Bill. "; nslog (@" % @ ", STR); STR = [STR camelcasestring]; nslog (@" % @ ", STR); [pool drain]; return 0 ;} 
  
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.