Object C学习笔记14-分类(category)

  在.NET中有一个非常带劲的特性,那就是扩展方法. 扩展方法使你能够向现有类型“添加”方法(包括你自定义的类型和对象噢),而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但是可以像扩展类型上的实例方法一样进行调用。

  先看看.NET中扩展方法的定义和使用

    public static class test
    {
        public static bool In(this object o, IEnumerable c)
        {
            foreach (object obj in c)
                if (obj.Equals(o))
                    return true;
            return false;
        }
    }
    string[] list = new string[] { "abc" , "123", "C#"};
    Console.WriteLine("Object C".In(list));

  在.NET中Object 类并没有In方法的定义,但是的确用"Object C"方法调用了In方法。

  Object C中的分类(category) 又称类别在不修改原有的类的基础上增加新的方法,和.NET一样不能添加新的实例变量。

  新增一个Person的Object C对象,在Person.h文件中定义相应的书属性name和age,并且定义一个方法:

  -(void) addName:(NSString*) name1 andWithAge:(int) age1;

#import <Foundation/Foundation.h>

@interface Person : NSObject{
    NSString *name;
    int age;
}

@property (retain) NSString *name;
@property (nonatomic)int age;

-(void) addName:(NSString*) name1 andWithAge:(int) age1;

@end
Person.h

  Person 类的详细描述文件如下:

#import <Foundation/Foundation.h>

@interface Person : NSObject{
    NSString *name;
    int age;
}

@property (retain) NSString *name;
@property (nonatomic)int age;

-(void) addName:(NSString*) name1 andWithAge:(int) age1;

@end
Person.m

  怎么调用这里就不说了,如果现在要往类Person中添加一个新的方法 

  -(void) addCate:(NSString*) cate;

 

  新建一个PersonCategory 类,产生.h,.m两个文件。

#import <Foundation/Foundation.h>
#import "Person.h"

@interface Person(cate)

-(void) addCate:(NSString*) cate;

@end

  在PersonCategory.h文件中修改为如上代码,将PersonCategory改为Person,并且后面括号为(cate)  ; () 中的名字可以随便取

#import "PersonCategory.h"

@implementation Person(cate)

-(void) addCate:(NSString *)cate{
    NSLog(@"dafdasfdsa=%@",cate);
}

@end

  修改PersonCategory.m文件中的代码如上。通过以上代码就可以往Person类中添加新方法 addCate 。

  测试调用addCate方法如下:

Person *peron=[[Person alloc] init];
        [peron addName:@"hechen" andWithAge:23];
        
        [peron addCate:@"safdasfds"];

  通过以上代码可以看得出 Person 可以调用addCate方法了,当然调用addCate方法需要引入文件PersonCategory.h 文件。

原文地址:https://www.cnblogs.com/qingyuan/p/3606208.html