Reputation: 217
I am making an iPhone app where a player uses a car. I want the player to be able to save setting on which car color they want to use. When i read the file that I have made to store the player's car's color my global NSString variable won't change values. here is my code:
NSString *carColor;
NSString *filePath2 = [[NSBundle mainBundle] pathForResource:@"carColor" ofType:@"txt"];
if(filePath2){
carColor = [NSString stringWithContentsOfFile:filePath2 encoding:NSUTF8StringEncoding error:NULL];
}
currentCarImage = [NSString stringWithString:carColor];
The variable carColor is assigned the right thing but when I look in the debugger it says that currentCarImage is an empty string. If I were to put this:
currentCarImage = @"greenCar.png";
It would work just fine. I even tried this:
NSString *filePath2 = [[NSBundle mainBundle] pathForResource:@"carColor" ofType:@"txt"];
if(filePath2){
currentCarImage = [NSString stringWithString:[NSString stringWithContentsOfFile:filePath2 encoding:NSUTF8StringEncoding error:NULL]];
}
But this also didn't work. Any ideas?
EDIT: I managed to get it to work in a way but it is still not really satisfactory. I changed my code to this:
NSString *carColor;
NSString *filePath2 = [[NSBundle mainBundle] pathForResource:@"carColor" ofType:@"txt"];
if(filePath2){
carColor = [NSString stringWithContentsOfFile:filePath2 encoding:NSUTF8StringEncoding error:NULL];
}
if([carColor isEqualToString:@"greenCar.png"]){
currentCarImage = @"greenCar.png";
}
if([carColor isEqualToString:@"blueCar.png"]){
currentCarImage = @"blueCar.png";
}
if([carColor isEqualToString:@"redCar.png"]){
currentCarImage = @"redCar.png";
}
if([carColor isEqualToString:@"purpleCar.png"]){
currentCarImage = @"pupleCar.png";
}
if([carColor isEqualToString:@"yellowCar.png"]){
currentCarImage = @"yellowCar.png";
}
if([carColor isEqualToString:@"turquoiseCar.png"]){
currentCarImage = @"turquoiseCar.png";
}
Upvotes: 0
Views: 377
Reputation: 112857
Not shown is hour you "made to store the player's car's color".
Guessing you tried to write it to the app bundle but that is not writable.
Either write to the app's Document directory or more simple use NSUserDefaults.
Example setting:
[[NSUserDefaults standardUserDefaults] setObject:carColor forKey:@"carColor"];
Example retrieving:
NSString *carColor = [[NSUserDefaults standardUserDefaults] stringForKey:@"carColor"];
Upvotes: 2
Reputation: 16316
You say carColor
gets assigned to the right thing. So why not bypass carColor
and directly assign currentCarImage
to stringWithContentsOfFile:
?
Upvotes: 0