zoukankan      html  css  js  c++  java
  • Objective-c Category(类别)

    category是Objective-c里面最常用的功能之一。

    category可以为已经存在的类增加方法,而不需要增加一个子类。

    类别接口的标准语法格式如下:

    1. #import "类名.h"  
    2. @interface 类名 (类别名)  
    3. //新方法的声明  
    4. @end  


    类别实现如下:

    1. #import "类名类别名.h"  
    2. @implementation 类名 (类别名)  
    3. //新方法实现  
    4. @end  


    这跟类的定义非常类似,区别就是category没有父类,而且在括号里面有category的名子。名字可以随便取。

    如:我们如果想在NSString上增加一个方法判断它是否是一个URL,那就可以这么做:

    1. #import …  
    2. @interface NSString (Utilities)  
    3. - (BOOL) isURL;  
    4. @end  


    类别实现:

    1. #import "NSStringUtilities.h"  
    2. @implementation NSString (Utilities)  
    3. - (BOOL) isURL{  
    4.   if( [self hasPrefix:@"http://"] )  
    5.       return YES;  
    6.   else   
    7.       return NO;  
    8. }  
    9. @end  


    使用方法:

    1. NSString* string1 = @"http://www.csdn.net";  
    2. NSString* string2 = @"Pixar";  
    3.   
    4. if( [string1 isURL] )  
    5.     NSLog(@"string1 is a URL");  
    6. else  
    7.     NSLog(@"string1 is not a URL");  
    8.   
    9. if( [string2 isURL] )  
    10.     NSLog(@"string2 is a URL");  
    11. else  
    12.     NSLog(@"string2 is not a URL");  



  • 相关阅读:
    酒店预订管理系统
    毕业论文管理系统
    酒店预订管理系统
    闪屏+引导页
    android编程测试
    测试用例
    ER图
    软件工程作业
    毕业论文管理系统
    酒店管理系统
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/4962996.html
Copyright © 2011-2022 走看看