我将给出一个代码,它可能会起作用并且应该小心使用。
我们定义了以下类类别:
@interface TheSpecificNSStreamClass (ProposedCategory)
@property (nonatomic, strong, readonly) NSArray* associatedRunLoops;
- (void)myScheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
- (void)myRemoveFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
@end
和实施:
@implementation TheSpecificNSStreamClass (ProposedCategory)
- (NSArray*)associatedRunLoops
{
return [NSArray arrayWithArray:objc_getAssociatedObject(self, @"___associatedRunloops")];
}
- (void)myScheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode
{
NSMutableArray* runloops = objc_getAssociatedObject(self, @"___associatedRunloops");
if(runloops == nil)
{
runloops = [NSMutableArray array];
objc_setAssociatedObject(obj, @"___associatedRunloops", runloops, OBJC_ASSOCIATION_RETAIN);
}
[runloops addObject:aRunLoop];
[self myScheduleInRunLoop:aRunLoop forMode:mode];
}
- (void)myRemoveFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode
{
NSMutableArray* runloops = objc_getAssociatedObject(self, @"___associatedRunloops");
[runloops removeObject:aRunLoop];
[self myRemoveFromRunLoop:aRunLoop forMode:mode];
}
@end
现在,在您的应用程序委托中的某个地方,我们使用方法调配将两个原始方法与我们的实现交换:
Method origMethod = class_getInstanceMethod([TheSpecificNSStreamClass class], @selector(scheduleInRunLoop:forMode:));
Method altMethod = class_getInstanceMethod([TheSpecificNSStreamClass class], @selector(myScheduleInRunLoop:forMode:));
if ((origMethod != nil) && (altMethod != nil))
{
method_exchangeImplementations(origMethod, altMethod);
}
origMethod = class_getInstanceMethod([TheSpecificNSStreamClass class], @selector(removeFromRunLoop:forMode:));
altMethod = class_getInstanceMethod([TheSpecificNSStreamClass class], @selector(myRemoveFromRunLoop:forMode:));
if ((origMethod != nil) && (altMethod != nil))
{
method_exchangeImplementations(origMethod, altMethod);
}
结果数组将具有所有关联NSRunLoop
的 s。