簡體   English   中英

為什么NSMutableDictionary不想寫入文件?

[英]Why NSMutableDictionary don't want write to file?

- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([[NSFileManager defaultManager] fileExistsAtPath:pathString]) 
    {
        infoDict = [[NSMutableDictionary alloc] initWithContentsOfFile:pathString];
    } 
    else 
    {
        infoDict = [[NSMutableDictionary alloc]initWithObjects:[NSArray arrayWithObjects:@"BeginFrame",@"EndFrame", nil] forKeys:[NSArray arrayWithObjects:[NSNumber numberWithBool:YES],[NSNumber numberWithBool:YES], nil]];
        if ([infoDict writeToFile:pathString atomically:YES])
        {
            NSLog(@"Created");
        } 
        else 
        {
            NSLog(@"Is not created");
            NSLog(@"Path %@",pathString);
        }
}

這是我的代碼。 我檢查文件是否已創建,如果沒有 - 我創建了一個NSMutableDictionary並將其寫入文件路徑,但writeToFile方法返回NO 哪里有問題? 如果我用NSFileManager創建這個文件它可以工作,但是當我想寫一個字典時卻沒有。

writeToFile:atomically僅在您調用它的字典是有效的屬性列表對象時才有效( 請參閱docs )。

要使NSDictionary成為有效的屬性列表對象,除其他外,其鍵必須是字符串 ,但在您的示例中,鍵是NSNumber實例。

您有時無法控制要寫入的內容。 例如,當您要編寫從服務器獲取的JSON對象時,您無法避免使用null值。

NSData與這些“無效”值兼容,因此在這些情況下將NSArrayNSDictionary轉換為NSData是一種理想的方法。

寫:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:jsonObject];
[data writeToFile:path atomically:YES];

讀:

NSData *data = [NSData dataWithContentsOfFile:path];
NSDictionary *jsonObject = [NSKeyedUnarchiver unarchiveObjectWithData:data];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM