【发布时间】:2011-04-29 21:52:39
【问题描述】:
我正在使用Stig Brautaset 的 JSON 框架序列化一些对象,包括 NSDates(不直接支持)。
我决定使用 NSDate 的描述作为日期的 JSONFragment 表示(我不关心这样做会导致精度的轻微损失)。
为了扩展 Stig Brautaset 的 JSON 框架以包含 NSDates,我定义了一个类别:
@interface NSDate (NSDate_JSON) <JSONInitializer>
-(NSString *) JSONFragment;
@end
为了从 JSON 重新创建 NSDate(和其他类),我使用以下初始化程序定义了一个协议:
@protocol JSONInitializer <NSObject>
-(id) initWithJSONRepresentation: (NSString *) aJSONRepresentation;
@end
我遇到了这个初始化程序的问题。在 NSDate 的情况下,它只是调用 initWithString:,这就是我遇到的麻烦:它总是返回 nil。这是实现:
#import "NSDate+JSON.h"
@implementation NSDate (NSDate_JSON)
-(NSString *) JSONFragment{
NSString *strRepr = [self description];
return [strRepr JSONFragment];
}
-(id) initWithJSONRepresentation:(NSString *)aJSONRepresentation{
return [self initWithString: aJSONRepresentation]; //returns nil!
}
@end
我不确定发生了什么。此外,编译器警告我 initWithJSONRepresentation: 中的 initWithString: 方法找不到。
有人知道会发生什么吗?
测试用例的完整源代码可在here 获得。
【问题讨论】:
-
aJSONRepresentation长什么样子? -
和NSDate的描述一模一样
-
@Bavarious 好的,你是对的,AJSONRepresentation 是双引号内的描述。
标签: objective-c cocoa protocols nsdate categories