我試圖通過使用鍵值編碼將它們轉換爲NSDictionary,然後JSONKit序列化各種對象,以便將NSDictionary序列化爲NSString/NSData。我遇到了轉換布爾屬性的問題。帶鍵值編碼和BOOL的JSONKit
KVC guidelines指出valueForKey:
對於BOOL屬性將通過[NSNumber numberWithBool:]
創建一個NSNumber。 JSONKit states that通過numberWithBool:
創建的NSNumber將被序列化爲true/false。我已經測試過JSONKit的說法,它的工作原理。但是,當我使用KVC訪問BOOL值時,我得到的對象看上去不像是通過numberWithBool:
創建的。特別是,它不會評估等於kCFBooleanTrue,JSONKit將其用作布爾值的標記。最終的結果是我的BOOL屬性被序列化爲0/1而不是true/false,這導致了接收API的問題。
如何確定KVC的NSNumber是否來自BOOL屬性?我誤解了Apple的文檔嗎?或者有其他方法可以使這個序列化過程起作用嗎?
下面是一個失敗的試驗:
#import "JSONKit.h"
- (void) testCompareKVCBoolToNumberWithBool {
NSNumber *numberBool = [NSNumber numberWithBool:YES];
//This passes
STAssertTrue(numberBool == (id)kCFBooleanTrue, @"Number %@ should kCFBooleanTrue.", numberBool);
TestModel *model = [[TestModel alloc] init];
model.boolProperty = YES;
NSNumber *kvcBool = [model valueForKey:@"boolProperty"];
//This fails
STAssertTrue(kvcBool == (id)kCFBooleanTrue, @"Number %@ should be a kCFBooleanTrue.", kvcBool);
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
numberBool, @"numberBool",
kvcBool, @"kvcBool",
nil];
NSString *jsonString = [dict JSONString];
//This yields: jsonString: {"kvcBool":1,"numberBool":true}
NSLog(@"jsonString: %@", jsonString);
}
這裏是TestModel代碼:
@interface TestModel : NSObject
@property (assign) BOOL boolProperty;
@end
@implementation TestModel
@synthesize boolProperty = _boolProperty;
@end
謝謝!
這有我的執行有同樣的問題,這是一個'BOOL'被轉換成'0'或'1',不'真「或」假「。查看https://gist.github.com/3762811瞭解更多詳情。 – jagill 2012-09-21 17:32:52
感謝您的反饋。將研究這個問題和你的實施。 :) – 2012-09-23 03:37:25