系统类,系统分类和自定义分类优先级

来源:互联网 发布:医学英语软件 编辑:程序博客网 时间:2024/06/14 13:27

在自定义的系统类(A)的分类中,重写A的系统属性和方法时,仍会优先调用系统的的属性和方法。重点内容 而重写A的系统分类的方法时,则会优先调用重写的方法。
例子:NSString
length 属性和 characterAtIndex:方法为系统方法,即使在自定义分类里重写,仍会优先调用系统的属性和方法
substringFromIndex: 方法是NSString的系统分类的方法,在自定义的分类里重写后,则会优先调用自定义的分类

NSString+test.h文件
@interface NSString (test)
/**
* 重写系统属性和方法
*/
- (NSUInteger)length;
- (unichar)characterAtIndex:(NSInteger)index;

/**
* 重写系统分类方法
*/
- (NSString *)substringFromIndex:(NSUInteger)from;
@end

NSString+test.m 文件
@implementation NSString (test)

  • (NSUInteger)length
    {
    return 10;
    }
  • (NSString *)substringFromIndex:(NSUInteger)from
    {
    return @”xxxxx”;
    }
  • (unichar)characterAtIndex:(NSInteger)index
    {
    return ‘r’;
    }
    @end

main.m main函数里调用
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here…

  NSString *str = @"Hello,everyone";  NSString *str1 = [str substringFromIndex:3];  unichar s = [str characterAtIndex:3];  NSLog(@"str.length : %ld",str.length);  NSLog(@"str1 : %@",str1);  NSLog(@"s : %c",s);}return 0;

}

输出结果为:
2017-07-13 22:34:10.831949+0800 MulInteranceDemo[10740:416546] str.length : 14
2017-07-13 22:34:10.831987+0800 MulInteranceDemo[10740:416546] str1 : xxxxx
2017-07-13 22:34:10.832004+0800 MulInteranceDemo[10740:416546] s : l