0

我正在尝试使用文本文件制作一个简单的受密码保护的应用程序来存储用户输入的密码。我想将文本字段中的内容存储在文件中,并最终将该文件中的内容与用户在另一个文本字段中输入的内容进行比较。这是我所拥有的:

 //Setting the string to hold the password the user has entered
    NSString *createPassword1 = passwordSet.text;

    //creating a muttable array to store the value of createPassword1
    NSMutableArray *passwordArray = [NSMutableArray array];

    //storing createpassword1 into the first element of the array
    [passwordArray addObject:createPassword1];

    NSLog(@"%@",[passwordArray objectAtIndex:0]);//seeing if it is stored correctly (it is)


    //path for searching for the file
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    //my filename
    NSString *fileName = @"PasswordFile.txt";

    NSString *fileAndPath = [path stringByAppendingPathComponent:fileName];

    if (![[NSFileManager defaultManager] fileExistsAtPath:fileAndPath]) {
        [[NSFileManager defaultManager] createFileAtPath:fileAndPath contents:nil attributes:nil];
    }

    [[[passwordArray objectAtIndex:0] dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAndPath atomically:YES];

任何帮助将不胜感激,谢谢。

4

1 回答 1

1

What you do is too complicated. Why do you use a NSMutableArray ("passwordArray") to store a single password? Why do you convert it to NSData and write this to a file? Just use a string and use its writeToFile method. Alternatively use NSArray's writeToFile method.

Alternatively, and my personal favorite: use NSUSerDefaults à la:

[[NSUserDefaults standardUserDefaults] setValue: myPasswordString forKey:@"appPassword"]];

EDIT in response to some comments: The above only applies if used in a "trivial" app that needs password-protection in a very low-level manner. Anything to protect really sensitive data should be handled differently. The original poster explicitly stated

I want to take whats in a text field store it in a file and ultimately compare whats in that file to what the user enters in another text field.

So one can assume that high-level security is not an issue here.

于 2012-12-17T19:21:29.347 回答