为什么我的[dictionary objectForKey:@“TOSAcceptedValue”]为空?

时间:2011-09-10 03:01:05

标签: objective-c null plist nsdictionary

我正在写文档目录中的plist并从中读取。首先,如果没有找到文件,我会写出文件。这似乎工作正常,因为起初没有文件,现在有双击该文件显示名为TOSAcceptedValue的键的预期内容,值为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)

为什么我无法获得TOSAcceptedStatus的任何线索?

另外,我是否允许在应用程序启动后写入和读取plist?

1 个答案:

答案 0 :(得分:2)

我认为你的主要问题是你有对象和密钥向后:

[appUsageNo setObject:value forKey:@"TOSAcceptedValue"];
相关问题