我知道通过使用类别来覆盖方法是一种不鼓励的做法。尽管如此,我必须处理一些执行此操作的代码。当我运行以下代码时,我最初对在这两种情况下都调用了我的类别方法感到惊讶,尽管考虑链接器必须如何在链接时为任何给定符号做出决定让我感觉更好。
我的问题:假设除了我创建的类别之外没有其他类别在起作用,我是否保证只要从某个地方导入它的标头,我的类别中的实现将始终是被调用的逻辑?
一些对象.h
#import <Foundation/Foundation.h>
@interface SomeObject : NSObject
- (void)doSomething;
@end
一些对象.m
#import "SomeObject.h"
@implementation SomeObject
- (void)doSomething
{
NSLog(@"Original");
}
@end
someObject+Cat.h
#import <Foundation/Foundation.h>
#import "SomeObject.h"
@interface SomeObject (SomeObject)
- (void)doSomething;
@end
someObject+Cat.m
#import "SomeObject+Cat.h"
@implementation SomeObject (SomeObject)
- (void)doSomething
{
NSLog(@"New!");
}
@end
一些ObjectUser.h
#import <Foundation/Foundation.h>
@interface SomeObjectUser : NSObject
- (void)useSomeObject;
@end
一些ObjectUser.m
#import "SomeObjectUser.h"
#import "SomeObject.h"
@implementation SomeObjectUser
- (void)useSomeObject
{
[[SomeObject new] doSomething];
}
@end
测试.m
- (void)testExample
{
[[SomeObject new] doSomething];
[[SomeObjectUser new] useSomeObject];
}
结果
2013-02-28 11:32:37.417 CategoryExample[933:907] New!
2013-02-28 11:32:37.419 CategoryExample[933:907] New!