Objective c 为什么我的[dictionary objectForKey:@“TOSAcceptedValue”为空?
我正在向我的文档目录中的plist写入和读取数据。首先,如果没有找到文件,我就把文件写出来。这似乎工作正常,因为起初那里没有文件,现在有了,双击该文件会显示名为Objective c 为什么我的[dictionary objectForKey:@“TOSAcceptedValue”为空?,objective-c,null,plist,nsdictionary,Objective C,Null,Plist,Nsdictionary,我正在向我的文档目录中的plist写入和读取数据。首先,如果没有找到文件,我就把文件写出来。这似乎工作正常,因为起初那里没有文件,现在有了,双击该文件会显示名为toAcceptedValue的键的预期内容,该键的值为no 但是如果文件被找到了,这发生在我运行上面一次之后,我尝试读取相同的值,我得到一个空值。这是代码,它可能不好看,因为我已经在黑客一段时间,让它的功能 NSError *error; NSString *TOSAcceptedStatus ; NSArray *paths = N
toAcceptedValue
的键的预期内容,该键的值为no
但是如果文件被找到了,这发生在我运行上面一次之后,我尝试读取相同的值,我得到一个空值。这是代码,它可能不好看,因为我已经在黑客一段时间,让它的功能
NSError *error;
NSString *TOSAcceptedStatus ;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog( @"paths is %@", paths);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"AppUsage.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
//first see if file exists. if it doesn't then write it out with a value of NO for Terms of Use Accepted
if (![fileManager fileExistsAtPath: path])
{
NSMutableDictionary *appUsageNo = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//here add element to data file and write data to file
NSString *value = @"NO";
[appUsageNo setObject:@"TOSAcceptedValue" forKey:value];
[appUsageNo writeToFile: path atomically:YES];
[appUsageNo release];
//and set TOSAcceptedStatus to no since we know its a no right now
TOSAcceptedStatus = @"NO";
}
else { //file was found at expected location so let's see if they accepted Terms of Use already
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
NSLog( @"path is %@", path);
TOSAcceptedStatus = [dictionary objectForKey:@"TOSAcceptedValue"];
//NSLog(@"TOSAcceptedStatus is %@", TOSAcceptedStatus);
NSLog(@"TOSAcceptedStatus is %@", [dictionary objectForKey:@"TOSAcceptedValue"]);
[dictionary release];
}
这是我的控制台结果
2011-09-09 21:47:23.177 myApp[1027:207] paths is (
"/Users/user1/Library/Application Support/iPhone Simulator/4.3/Applications/34562D85-DBE9-4A4F-A142-JEFC1F4808D1/Documents"
)
2011-09-09 21:47:44.915 myApp[1027:207] path is /Users/user1/Library/Application Support/iPhone Simulator/4.3/Applications/34562D85-DBE9-4A4F-A142-JEFC1F4808D1/Documents/AppUsage.plist
2011-09-09 21:47:50.448 myApp[1027:207] TOSAcceptedStatus is (null)
有什么线索可以告诉我为什么我不能返回到AcceptedStatus
吗
另外,在应用程序启动后,是否允许我向plist进行写操作和读操作 我认为您的主要问题是对象和键向后:
[appUsageNo setObject:value forKey:@"TOSAcceptedValue"];
[[NSMutableDictionary alloc]dictionaryWithContentsOfFile:path]代码>--这似乎有点荒谬。为什么要创建一本词典,扔掉它,然后再创建第二本呢。如果第二个已经自动释放了,为什么还要释放它呢?在上面的声明中,我肯定有我的键和值。谢谢你能听到。当然,很高兴能为你服务!尝试执行NSLog(@“%@,[dictionary description])代码>,以查看您得到了什么。“TOSAcceptedValue”可能不在字典中。这与以下代码一样有帮助:for(dictionary中的id key){NSLog(@“key:%@,value:%@),key,[dictionary objectForKey:key]);也很有帮助。它帮助我更好地了解了plist的结构。感谢您的帮助。