gpt4 book ai didi

ios - 以编程方式创建的 plist 并尝试通过 Apple 的指南读取,要么无法正确创建,要么无法正确读取

转载 作者:行者123 更新时间:2023-11-29 04:11:02 27 4
gpt4 key购买 nike

变量:

NSMutableDictionary *rootObj;
NSDictionary *innerDict;
NSString *name;
NSArray *scores;

代码:

rootObj = [NSMutableDictionary dictionaryWithCapacity:2];

scores = [NSArray arrayWithObjects:[NSNumber numberWithInt:6],
[NSNumber numberWithFloat:4.6], [NSNumber numberWithLong:6.0000034], nil];
name = @"George Washington";



innerDict = [NSDictionary dictionaryWithObjects:
[NSArray arrayWithObjects: name, scores, nil]
forKeys:[NSArray arrayWithObjects:@"Name", @"Scores", nil]];
[rootObj setObject:innerDict forKey:@"Washington"];

scores = [NSArray arrayWithObjects:[NSNumber numberWithInt:8],
[NSNumber numberWithFloat:4.9],
[NSNumber numberWithLong:9.003433], nil];
name = @"Abraham Lincoln";


innerDict = [NSDictionary dictionaryWithObjects:
[NSArray arrayWithObjects: name, scores, nil]
forKeys:[NSArray arrayWithObjects:@"Name", @"Scores", nil]];
[rootObj setObject:innerDict forKey:@"Lincoln"];

id plist = [NSPropertyListSerialization dataFromPropertyList:(id)rootObj
format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];

// SERIALIZATION

NSString *path = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
NSData *xmlData;
NSString *error;

xmlData = [NSPropertyListSerialization dataFromPropertyList:plist
format:NSPropertyListXMLFormat_v1_0
errorDescription:&error];
if(xmlData) {
NSLog(@"No error creating XML data.");
[xmlData writeToFile:path atomically:YES];
NSFileManager *manger = [[NSFileManager alloc] init];
NSLog(@"%@", [manger contentsAtPath:path]);
}
else {
NSLog(@"error");
// [error release];
}

NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
NSLog(@"%@", myDictionary);

输出是:

2013-01-18 14:33:50.066 PListTrials[11281:c07] No error creating XML data.
2013-01-18 14:33:50.067 PListTrials[11281:c07] (null)
2013-01-18 14:33:50.067 PListTrials[11281:c07] (null)

myDictionary 为何为空?代码取自:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/CreatePropListProgram/CreatePropListProgram.html#//apple_ref/doc/uid/10000048i-CH5-SW1

最佳答案

您无法在应用程序主包上​​写入内容。在文档包中执行此操作

最初,您的 plist 文件“Data.plist”不存在于路径中,因此您需要创建它。每当您想要写入数据时,最好检查该文件是否存在。请尝试以下操作:

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"Data.plist"];
if ([fileManager fileExistsAtPath:path] == NO) {
[fileManager createFileAtPath:path contents:YourContent attributes:nil];
}else {
[Content writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

关于ios - 以编程方式创建的 plist 并尝试通过 Apple 的指南读取,要么无法正确创建,要么无法正确读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14406412/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com