I'm making an app involving saving data to a textfield and loading it back. It's working in the simulator but not in on my actual iPhone. Why so?

StackOverflow https://stackoverflow.com/questions/11436105

سؤال

In the program I use this method to create a file in which I can save:

-(NSString*) saveFilePath{
NSString* path = [NSString stringWithFormat:@"%@%@",
                  [[NSBundle mainBundle] resourcePath],
                  @"savingfile.plist"];
return path;}

Then I used a button to initiate the process of putting the data into the file (I first put it all into an array so that it would be easier.):

- (IBAction)save
{

NSMutableArray *myArray = [[NSMutableArray alloc] init];
[myArray addObject:name.text];
[myArray addObject:position.text];
[myArray addObject:cell.text];
[myArray addObject:office.text];
[myArray addObject:company.text];
[myArray writeToFile:[self saveFilePath] atomically:YES];

}

Finally, I loaded the information back into the textfields in the - (void)viewDidAppear method.

- (void)viewDidAppear:(BOOL)animated
{
NSMutableArray* myArray = [NSMutableArray arrayWithContentsOfFile:[self saveFilePath]];
name.text = [myArray objectAtIndex:0];
position.text = [myArray objectAtIndex:1];
cell.text = [myArray objectAtIndex:2];
office.text = [myArray objectAtIndex:3];
company.text = [myArray objectAtIndex:4];
}

For some reason, on the simulator it's working perfectly on the simulator, but not working at all when I try to run on my physical iPhone.

هل كانت مفيدة؟

المحلول

I think you're trying to save to a location that's read-only on iOS. It works on the simulator because the simulator doesn't totally replicate the sandboxing environment on the actual hardware.

Rather than saving to the resourcesPath you should be saving your files to the Documents directory (or the cache directory, if appropriate).

You can get a path to the documents directory as follows:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

There's more information at this question here: How to save file in resource folder of an app in Objective-c

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top