I'm trying to separate the methods for the NSCoding into separate files from my actual classes. I know you can generally define new methods using Categories in Objective-C, but it seems Xcode still sends warnings when it doesn't encounter the -encodeWithCoder: and -initWithCoder: methods in the master class file.
The reason I'm doing this (and hopefully this doesn't sound too convoluted) is that I have many dozen classes spread across various files, and in order to avoid the tedium and redundancy of writing out encodeWithCoder:/initWithCoder: methods for each and every class, I put together a small script to automatically parse the header files and generate the necessary encoding/decoding code based on variable types and dump the results into a single Encoders.m. The result links properly, but I still receive the warnings during compilation "Incomplete implementation of class 'MyClass'", "Method definition for '-initWithCoder:' not found" (etc), and "Class 'MyClass' does not fully implement the 'NSCoding' protocol". I've tried simply adding the declarations to the classes' .h files, but no go.
Is there any way to inform Xcode that the methods are in fact implemented, just not in the non-Category class file?开发者_JS百科
A simplified example:
MyClass.h
@interface MyClass : NSObject <NSCoding> {
int num; //@ENCODABLE
float timer; //@ENCODABLE
SomeOtherClass *obj; //@ENCODABLE
}
...
@end
MyClass.m
#import "MyClass.h"
@implementation MyClass
...
@end
Encoders.m
#import "MyClass.h"
@implementation MyClass (Encoding)
-(void) encodeWithCoder:(NSCoder*)encoder {
// Auto-generated encoding of instance variables
}
-(id) initWithCoder:(NSCoder*)decoder {
if (self = [self init]) {
// Auto-generated decoding of instance-variables
}
return self;
}
@end
Any methods which are declared in the class's interface, a class extension, or a protocol which either the interface or extension specify, must be implemented in the main @implementation
block, or you will receive a warning. There is no way to declare a method in those places and tell the compiler it will be in a category. What you can do is create a category interface and declare the NSCoding
protocol there. If you add this interface to your main header file, any files which import the header will know that the class supports coding, but the compiler won't complain that the methods aren't implemented.
New MyClass.m
@interface MyClass : NSObject {
int num; //@ENCODABLE
float timer; //@ENCODABLE
SomeOtherClass *obj; //@ENCODABLE
}
...
@end
@interface MyClass (Encoding) <NSCoding>
@end
精彩评论