1

My question is simple. I want to extend the NSMutableData class in iOS and override some of the methods defined in NSMutableData. For e.g. I want to override writeToFile function with my own wrapper implementation for it. Is it possible to do this?

My TestNSMutableData.h

@interface TestNSMutableData : NSMutableData
-(BOOL)writeToFile:(NSString*)path atomically:(BOOL)useAuxiliaryFile;
@end

My TestNSMutableData.m

@implementation TestNSMutableData
-(BOOL)writeToFile:(NSString*)path atomically:(BOOL)useAuxiliaryFile{
  //Some activity on the data and modifying it
  return [self writeToFile:path atomically:useAuxiliaryFile];
}

When I try to use the TestNSMutableData in one of my project like

TestNSMutableData myData;
myData = [TestNSMutableData alloc]init];
[myData writeToFile:path atomically:YES]

I get an error as follows

NSInvalidArgumentException'- reason '* - length only defined for abstract class. Define -[TestNSMutableData length] !

Is it possible at all to override the methods defined in Native classed for e.g. NSMutableData ?

UPDATE I create NSString class category method for writeTofile

My implementation is

-(BOOL)writeToFile:(NSString*)path atomically:(BOOL)useAuxiliary encoding:(NSStringEncoding)enc error:(NSError**)error{


 //Manipulating NSString 
  self = manipulatedString;
  return [super writeToFile....];

}

I get a warning "NSObject may not respond to 'writeToFile' function. Which is technically correct as NSString is derived from NSObject and NSObject does not have writeToFile function.

What I want is to write the manipulated string in the file and not the actual string.

Is there a way to call the NSString writeToFile method from the above function.

Regards,

Nirav

Nirav
  • 315
  • 1
  • 4
  • 16

1 Answers1

1

NSMutableData is probably a class cluster, making it a bit hard to subclass. Why not use a category to add a custom -writeToFile method instead?

Community
  • 1
  • 1
zoul
  • 102,279
  • 44
  • 260
  • 354
  • If I add a category and the methods signature is what the native has, it gives me compilation error wherever I instantiate the TestNSMutableClass (it says Did you mean NSMutableClass) – Nirav Sep 11 '12 at 08:50
  • If you add a category, there’s no `TestNSMutableData`, right? You can’t (or shouldn’t) override a method using category, you would have to add a method with a different signature. If you really need to override the original method, I’d suggest wrapping `NSMutableData` in a custom class and forwarding all calls except the overriden one. Or, even better, trying to solve your main problem in a different way. – zoul Sep 11 '12 at 09:14
  • Thanks Zoul !! I finally achieved it using the Category (I was trying to create manually rather than using XCode). Thanks again !! – Nirav Sep 12 '12 at 05:55