简体   繁体   中英

where does the text file I dragged to xcode go on the iphone/simulator?

I have some data in a .txt file that I dragged over to resources in xcode 4.2. I then use some methods that call upon this file, read it, and display it on the screen to the user. It works. My problem is writing to the end of the same file (aka updating the file based on something the user did) directly on the iphone/ the simulator. It does not write for I feel I am not calling upon the right location and perhaps method. This is my code to write to the end of file, if anyone knows why this is not working it would be tremendous help.

Thank you

-(void)updateFile:(id)sender

{

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



    //append filename to docs directory
    NSString *myPath =  [documentsDirectory stringByAppendingPathComponent:@"Mom.txt"];


    fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:myPath];

    dateCombinedString= [dateCombinedString lowercaseString];
    writtenString= [[NSString alloc]initWithFormat:@", %@, %@, %@",dateString,trimmedString,ForDisplay];


    [fileHandle seekToEndOfFile];
    [fileHandle writeData:[writtenString    dataUsingEncoding:NSUTF8StringEncoding]];

      [writtenString release]

         }

The file you dragged to Xcode is inside your app resources. You can get the path to resource with this line of code:

NSURL* fileUrl = [[NSBundle mainBundle] URLForResource:@"Mom" withExtension:@"txt"];

However, you cannot modify the files in the resource directory therefore you should first copy that file to your document directory, then modify it with the code in the question.

Here is how you can copy file from resources if the file does not exist on the documents folder:

NSFileManager* fm;

fm = [NSFileManager defaultManager];
//only copy it from resources if it does not exits
if(![fm fileExistsAtPath:myPath]){
  NSURL* myUrl = [NSURL fileURLWithPath:myPath];;
  NSError* error = nil;
  [fm copyItemAtURL:fileUrl toURL:myUrl error:&error];
  //handle the error appropriately
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM