setValue:forKey:带有NSString

时间:2012-11-07 21:28:23

标签: iphone objective-c nsstring

我目前正在开发一个小型的特定iPhone应用程序来连接服务器并下载一些JSON数据。我的问题是关于我用来保存一些数据(登录,密码和服务器域)的属性列表。我很容易在Xcode中创建了plist但是当我尝试使用用户输入的文本编辑它时,我遇到了问题,我不知道如何解决它......

这是textFieldDidEndEditing: method,其中我尝试使用用户在domainTextField中编写的内容写入plist:

- (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。我试图把反斜杠,但这没有帮助。

我该怎么做才能解决此错误?

1 个答案:

答案 0 :(得分:0)

如果字符串中有任何参数,StringWithFormat将使用,因此您可以直接指定字符串值,如下所示

NSString *domain = self.domainTextField.text;
相关问题