0%

《Objective-C 编程》37.Category 范畴

  • 通过使用范畴(category,范畴、分类),可以为任何已有的类添加方法。
  • ⚠️ 建议使用带有前缀(bnr_)的方法:实现了使用范畴的方法时,如果在类中已经存在名称相同的另一个方法,这个使用了范畴的方法就会替换掉之前存在的方法。
  • 应该使用范畴来给已存在的类增加新方法,而不要在范畴中替换已经存在的方法:这种情况下应该创建该类的子类。

示例:

NSDate 类添加一个创建日期的类方法:

image

  • NSDate+VowelCounting.h 文件

    <!–hexoPostRenderEscape:

    #import <Foundation/Foundation.h>

@interface NSDate (VowelCounting)

  • (NSString *)bnr_createCustomDate;

@end:hexoPostRenderEscape–>

  • NSDate+VowelCounting.m 文件

    <!–hexoPostRenderEscape:

    #import "NSDate+VowelCounting.h"

@implementation NSDate (VowelCounting)

  • (NSString *)bnr_createCustomDate {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    return [dateFormatter stringFromDate:[NSDate date]];
    }

@end:hexoPostRenderEscape–>

  • 使用

    NSString *date = [NSDate bnr_createCustomDate];

欢迎关注我的其它发布渠道