objective-c(类别)

objective-c中的Categary(类别)使用相当广泛,其内涵类似于javascript中的prototype,可以扩展某一个类的方法。

下面给出一个基本的例子,参考oc程序设计一书:

  • 实现一个categary
#import <Foundation/Foundation.h>

@interface NSString(Util) //在NSString的基础上实现Util类别

-(BOOL)isUrl;

@end

#import "NSString+Util.h"

@implementation NSString(Util)

-(BOOL)isu
{
    if([self hasPrefix:@"http"]){
        return TRUE;
    }else{
        return FALSE;
    }
}

@end
  • 测试代码
#import <Foundation/Foundation.h>
#import "NSString+Util.h" //包含头文件则开始使用此类别

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSString *test1 = @"http://lcacds";
        NSString *test2 = @"fdsfs";
        
        if([test1 isUrl]){ //判断是否是一个URL链接
            NSLog(@"%@ is url", test1);
        }else{
            NSLog(@"%@ not url", test1);
        }
        
        if([test2 isUrl]){
            NSLog(@"%@ is url", test2);
        }else{
            NSLog(@"%@ not url", test2);
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/Fredric-2013/p/4297028.html