[英]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
創建這個文件它可以工作,但是當我想寫一個字典時卻沒有。
您有時無法控制要寫入的內容。 例如,當您要編寫從服務器獲取的JSON對象時,您無法避免使用null
值。
NSData
與這些“無效”值兼容,因此在這些情況下將NSArray
或NSDictionary
轉換為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.