Reputation: 1619
I have a file within my iOS app called coins.txt, which I use to record the number of coins the player has. Each time the app is started, the file is read to determine how many coins the player has using this file path:
var cFilePath: String! = NSBundle.mainBundle().pathForResource("coins", ofType: "txt")
I can read from the file using this file path just fine, as well as write to it, but the problem is that I'm currently using a simulator since I don't have access to an iPhone with iOS 8 yet, and every time the app is run in the simulator, a new file path is created, which I assume is because I'm essentially installing and uninstalling the app over and over and the app on the simulator is separate from the app I edit in Xcode, and the simulator doesn't provide a way to regularly return to the home screen. So any changes made to the coins don't stay, since every time the app is run again, the number of coins becomes the number designated to the coins.txt file in the app which hasn't been changed. Will this problem remain when the app is installed on a physical device?
Also, when the app is released to the App Store and I upload an update, since the default content of the coins.txt file is 0 and updating an app is just replacing the old app with the new one, will the player's coins be reset to 0? If so, how can I prevent this from happening?
Thanks in advance!
Upvotes: 0
Views: 1391
Reputation: 17104
You can read from the mainBundle but cannot write to it. You will need to copy your file to another directory (consider the caches directory) and read/write there.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"coins.text"];
NSData *coinsData = [NSData dataWithContentsOfFile:filePath];
However, perhaps more appropriate for what you are trying to achieve (light weight data storage) would be using NSUserDefaults.
Edit
// Setting
NSUserDefaults.standardUserDefaults().setInteger(10, forKey: "coins")
NSUserDefaults.standardUserDefaults().synchronize()
// Getting
var coins = NSUserDefaults.standardUserDefaults().integerForKey("coins")
Upvotes: 2