【发布时间】:2012-11-07 21:28:22
【问题描述】:
我目前正在开发一个小型且特定的 iPhone 应用程序来连接到服务器并下载一些 JSON 数据。我的问题是关于我用来保存一些数据(服务器的登录名、密码和域)的属性列表。我在 Xcode 中轻松创建了 plist,但是当我尝试使用用户输入的文本对其进行编辑时,我遇到了问题,我不知道如何解决它...
这是textFieldDidEndEditing: method,我尝试在其中写入 plist,其中包含用户在 domainTextField 中写入的内容:
- (void)textFieldDidEndEditing:(UITextField *)textField
{
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filepath = [NSString stringWithFormat:@"%@/userInfo.plist", [paths objectAtIndex:0]];
NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] initWithContentsOfFile:filepath];
if (self.domainTextField) {
NSString *domain = [NSString stringWithFormat:@"%@", self.domainTextField.text];
[userInfo setValue:domain forKey:@"domain"];
}
if ([userInfo writeToFile:filepath atomically:TRUE]) {
NSLog(@"write succeeded");
} else {
NSLog(@"write failed");
}
}
我总是在这里收到“写入失败”错误,在使用调试器玩了一会儿之后,我发现问题出在 setValue:forKey: method 上。事实上,我希望这个方法可以在 plist 中写入:domain = "whateverthedomainis",因为domain 是一个 NSString,但它改为写入:domain = whateverthedomainis。由于 writeToFile:atomically: 方法确保所有对象都是属性列表对象,因此它返回 NO。我尝试添加反斜杠,但没有帮助。
我可以做些什么来解决这个错误?
【问题讨论】:
-
我认为您可能需要转义该字符串,我会使用二进制保存方法而不是 plist one
-
感谢您的评论。我会尝试二进制方法,但我很惊讶他们没有二进制就无法做到这一点
-
您是否尝试过使用
NSMutableDictionary方法setObject:forKey:而不是Key-Value-Coding? -
我刚刚尝试过,结果很奇怪:
[userInfo writeToFile:filepath atomically:TRUE]看起来是 YES,因为我有NSLog(@"write succeeded");但是当我检查 plist 时,新域未设置。 ..
标签: iphone objective-c nsstring