Not able to swizzle NSOutputStream's write:MaxLength:

155 views Asked by At

I have a requirement of writing a custom data, before the actual write of NSOutputStream happens.

To make swizzling code execute, i have created a category NSOutputStream(SwizzleWrite), which contains the following:

SEL originalSelector = @selector(write:maxLength:);
SEL swizzledSelector = @selector(swizzledWrite:maxLength:);

Method originalMethod = class_getInstanceMethod([NSOutputStream class], originalSelector);
Method swizzledMethod = class_getInstanceMethod([self class], swizzledSelector);

method_exchangeImplementations(originalMethod, swizzledMethod);

I then create Inout & Output stream: CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, hostRef, 80, &readStream, &writeStream);

inputStream = (__bridge_transfer NSInputStream *)readStream;
outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];

But now when the control reaches handleEvent: delegate, specifically on: [outputStream write:rawstring maxLength:sizeof(rawstring)];, i do not get it on swizzledWrite:maxLength:

What am i doing wrong here?

PS: I have read that swizzling Apple methods is not Appstore-friendly, but i have also read cases where they are accepted.

1

There are 1 answers

5
Yaser On

Why do you feel that swizzling is the best option here? Sounds to me like a subclass would be much better. There are some tricky parts about subclassing a stream but take a look here

If you are determined to make swizzling work, have you set breakpoints and made sure that your swizzling selectors are not nil? Might happen if you get the signatures a bit wrong