OC之category的用法

  • 简介
  • 实例
  • 好处

一、category简介

动态的为某个已经存在的类增加方法,不可以增加成员变量

二、实例

//
//  Student+CatetoryStudent.h
//  Category
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import "Student.h"

@interface Student (CatetoryStudent)

-(void) test;

@end
//
//  Student+CatetoryStudent.m
//  Category
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import "Student+CatetoryStudent.h"

@implementation Student (CatetoryStudent)

-(void)test
{
    NSLog(@"test");
}

@end
//
//  main.m
//  Category
//
//  Created by apple on 14-3-26.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Student.h"
#import "Student+CatetoryStudent.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        Student *stu = [[[Student alloc] init] autorelease];
        
        [stu test];
        
    }
    return 0;
}

三、总结

在什么时候用category比较好?

1⃣️需求改变

2⃣️土堆合作

3⃣️对系统类扩展,比如给NSString类增加一个处理Json的方法

posted @ 2014-03-26 16:21  了透糕糟  阅读(372)  评论(0编辑  收藏  举报