问题
In my app, I have a simple ASCII file which stores some config info and other small info which it uses and changes. I want to copy that file to the iPhone with the app.
1) Please tell me where I should put this file (config.txt) in xcode. Should I put it under Resources ?
2) How will I access it in the iPhone ? Can I just use
str = [NSString stringWithContentsOfFile:@"config.txt"]
or do I have to use a more complete path; if yes, what is that ?
回答1:
You should use NSUserDefaults
to store user settings, if the application can change them.
The documentation is here.
The settings are stored as a plist file, so you can store NSDictionary
instances, NSArray
instances, etc.
If you want to pre-populate your NSUserDefaults
with some settings, you can do so with some code like this one:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"defaults" ofType:@"plist"];
NSDictionary *defaultsDict = [NSDictionary dictionaryWithContentsOfFile:filePath];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsDict];
You need to put a defaults.plist file on your Resources folder with the default settings, and use the code above. I run that code from the AppDelegate's +(void)initialize
method, but you can choose another place to call it.
回答2:
You can put it in Resources, yes. To get the file, then, you can simply use:
[[NSBundle mainBundle] pathForResource:@"config" ofType:@"txt" inDirectory:@""]]
May I suggest NSUserDefaults
for your settings, however? It will save you plenty of trouble in reading and writing them.
回答3:
And if you want to retrieve the NSUserDefaults, you can do the following:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting a NSString
NSString *myString = [prefs stringForKey:@"keyToLookupString"];
// getting a NSInteger
NSInteger myInt = [prefs integerForKey:@"integerKey"];
// getting a Float
float myFloat = [prefs floatForKey:@"floatKey"];
回答4:
If nsuserdefaults doesn't meet your needs, you could store the config information in a file in the Documents directory. If the file doesn't exist on startup, then read the version you have in Resources.
来源:https://stackoverflow.com/questions/789397/iphone-app-where-do-i-put-a-config-file