在Objective C中是否有任何方法,类或任何内容可以检测或检测是否已调用Method?所以,我可以在if语句中写出来。
答案 0 :(得分:2)
如果您拥有该方法的实现,则可以在进入和退出方法时使用NSNotificationCenter发布通知。我做了something like this一段时间,但是因为财产的变化。你可以实现基本相同的东西。
创建我们的API,只暴露专用的初始化程序,我们提供我们正在监视的对象和我们想要在对象具有属性更改时调用的方法。如果您愿意,可以重写这个以使用代码块。我在编写代码块之前写了这个。
#import <Foundation/Foundation.h>
@interface ObjectMonitor : NSObject
- (id)initWithMonitoringObject:(NSObject *)objectToMonitor respondingWithSelector:(SEL)selector;
@end
现在您只需实现专用的初始化程序,它将对象属性分解为集合并将自身注册为KVO观察者。只要observeValueForKeyPath
中的任何属性发生更改,objectToMonitor
方法就会被触发。
#import "ObjectMonitor.h"
#import <objc/objc-runtime.h>
@interface ObjectMonitor ()
@property (nonatomic) SEL selector;
@end
@implementation ObjectMonitor
- (id)initWithMonitoringObject:(NSObject *)objectToMonitor respondingWithSelector:(SEL)selector {
self = [super init];
if (self) {
self.selector = selector;
unsigned int count;
objc_property_t *properties = class_copyPropertyList([objectToMonitor class], &count);
for (size_t i = 0; i < count; ++i) {
NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])];
[objectToMonitor addObserver:self forKeyPath:key
options:0 context:NULL];
}
free(properties);
}
return self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
NSLog(@"%@ had %@ changed!", NSStringFromClass([object class]), keyPath);
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[[object class] instanceMethodSignatureForSelector:self.selector]];
if (invocation) {
invocation.target = object;
invocation.selector = self.selector;
@try {
[invocation invoke];
}
@catch (NSException *exception) {
NSLog(@"Failed to invoke the method");
}
@finally {
}
} else {
NSLog(@"ERROR: Failed to locate the method for @selector:%@", NSStringFromSelector(self.selector));
}
}
@end
实例ObjectMonitor,将方法回调与它相关联,你就可以了。 savePlayerSettings
MYPlayerSettings
方法
#import "MYPlayerSettings.h"
#import "ObjectMonitor.h"
@interface MYPlayerSettings ()
@property (strong, nonatomic) ObjectMonitor *objectMonitor;
@end
@implementation MYPlayerSettings
-(id)init {
self = [super init];
if (self) {
self.objectMonitor = [[ObjectMonitor alloc]
initWithMonitoringObject:self
respondingWithSelector:@selector(playerSettingsChanged)];
}
return self;
- (void)playerSettingsChanged {
NSLog(@"%@ had settings changed", self.name);
}
我知道您希望收到有关方法调用的通知,但是您可以通过传入要调用的方法稍微修改一下,然后在每次触发方法的名称时更改专用的NSString属性。方法。然后在回调处理程序中,根据更改的值检查触发的方法,并做出相应的反应。
希望这有帮助。