zoukankan      html  css  js  c++  java
  • Objective-C基调(4)Category

    OC它提供了一种不同的方式--Category,可以动态地添加新的行为已经存在的类(方法),这确保了较小的类的原始设计,然后逐渐加入扩展。

    正在使用Category扩张的上课时间,你并不需要创建一个子类,Category使用简单的方法。实现类模块化的相关方法,类方法分配到不同的分类文件里。

    以下我们通过三个分类样例来看一下怎样使用分类:

    接着我们上一篇的代码,以下我们创建一个Student的Test分类。创建步骤例如以下:




    注意上面的Student+Test.h和Student+Test.m这两个文件就是我们为Student类创建的分类文件

    Student+Test.h文件

    #import "Student.h"
    
    @interface Student (Test)
    
    - (void)test;
    
    @end
    Student+Test.m文件

    #import "Student+Test.h"
    
    @implementation Student (Test)
    
    - (void) test {
        NSLog(@"调用了Student的Test分类的test方法");
    }
    
    @end
    main.m文件

    #import <Foundation/Foundation.h>
    #import "Student.h"
    #import "Student+Test.h"
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            Student *stu = [[[Student alloc] initStudent:23] autorelease];
            [stu test];
        }
        return 0;
    }
    执行结果:

    2014-11-16 11:32:00.861 内存管理[582:33690] 年龄为23的学生被创建了

    2014-11-16 11:32:00.862 内存管理[582:33690] 调用了Student的Test分类的test方法

    2014-11-16 11:32:00.862 内存管理[582:33690] 年龄为23的学生被释放了

    分类除了这样的写法事实上能够直接写到Student.h和Student.m中,而不用单独创建文件。

    我们也能够给系统的类(NSString)进行分类,比方我们给NSString加入一个处理json的方法。

    #import <Foundation/Foundation.h>
    
    @interface NSString (JSON)
    
    + (void)json;
    
    @end
    #import "NSString+JSON.h"
    
    @implementation NSString (JSON)
    
    + (void) json{
        NSLog(@"{'nam':'CodeingSnal', 'age',24");
    }
    
    @end

    分类的使用场景:

    1、在定义类的某些情况下(比如需求变更)。你可能须要给当中的某个或某几个类加入新的方法。

    2、一个类中包括了很多不同种类的方法须要实现。而这些方法须要不同的团队的成员实现。

    3、在使用基础类库的类时,有可能希望这些类实现一些自己须要的方法,比方写个NSString+JSON.h,至NSString这个类是开发一些解决JSON方法。


    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    [CLYZ2017]day10
    标签
    FJOI2017一试滚粗
    [学习笔记]一些求gcd的方法的证明
    WC2017有感
    [学习笔记]splay
    [CLYZ2017]day9
    [CLYZ2017]day6
    转:Asp.net模板引擎技术(html)
    精华:ASP.NET开发网站程序安全解决方案(防注入等)
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/4709729.html
Copyright © 2011-2022 走看看