Question

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

Was it helpful?

Solution

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top