NSString combine date and name as the name of a csv - ios

I have an iOS app that gets data from a form and then sends it as a csv via email. currently it saves the csv as a static file name but i want it to start saving it as <date><other app defined variable>.csv. If its easier to redefine a new variable for the date then so be it, have tried it but couldn't make that work either.
Currently it looks like this:
NSString* fileName = #"file.csv";
I have tried this, among other minor syntax changes with no luck:
NSString* fileName = #"%#%# .csv",FromEmail,dateString;
FromEmail is defined in HomeView.m like this:
NSString *FromEmail = [userDefault objectForKey:#"FromEmail"];
This is the whole csv making part:
//CSV function
NSMutableString *csv = [NSMutableString stringWithString:#""];
//add your content to the csv
[csv appendFormat:#"From,Date,Client,Time,Notes,Hardware,AfterHours,NoCharge\n%#,%#,%#,%#,%#,%#,%#,%#",FromEmail,dateString,txtClient.text,txtTime.text,txtNotes.text,txtHardware.text,isAfterHours,isDiscount];
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//NSString* fileName = #"file.csv";
NSString* fileName = #"%#%# .csv",FromEmail,dateString;
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
[[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
}
BOOL res = [[csv dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
if (!res) {
[[[UIAlertView alloc] initWithTitle:#"Error Creating CSV" message:#"Check your permissions to make sure this app can create files so you may email the app data" delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles: nil] show];
}else{
NSLog(#"Data saved! File path = %#", fileName);
[picker addAttachmentData:[NSData dataWithContentsOfFile:fileAtPath]
mimeType:#"text/csv"
fileName:#"file.csv"];
[self presentViewController:picker animated:YES completion:nil];
}
//END CSV Function
I suspect its something really simple but its just had me stumped for ages

Hot Licks was right, I had the format of the date wrong. It was throwing an error because the date section was formatted with forward slashes which was changing the path it was being saved at.
I added a separate date formatter for the CSV file name with this code:
NSDate *csvDate = [NSDate date];
NSDateFormatter *csvFormatter = [[NSDateFormatter alloc] init];
[csvFormatter setDateFormat:#"ddMMyy-Hm"];
NSString *csvDateString = [csvFormatter stringFromDate:csvDate ];
And changed the line making the filename variable to this:
NSString* fileName = [NSString stringWithFormat:#"%#%#.csv",FromEmail,csvDateString];
Thanks for the help

Related

UIDocumentPickerViewController copied files disappear on download to test iPad

I am using UIDocumentPickerViewController to allow the user to select files that will be "attached" and available within the App. The concept is allow the user to send detail via email with the selected file attachments.
As each file is attached, I copy the file from the tmp Inbox (where fileManager puts the imported file) to a directory I create within the App document directory called "fileAttachments".
I list the files in a UITableView and the user can select each entry and preview the content within a QLPreviewController view using the path stored in the file object fileOJ.filePath.
It all works swimmingly well, until a reload of the project down to my test iPad, then all the files seem to disappear. My list of the files is still fine, but there is no file at the path location.
Any help with just what is happenning would be greatly appreciated.
- (IBAction)selectFilesAction:(UIBarButtonItem *)sender {
NSArray *UTIs = [NSArray arrayWithObjects:#"public.data", nil];
[self openFilePicker:UTIs];
}
- (void)openFilePicker:(NSArray *)UTIs {
UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:UTIs inMode:UIDocumentPickerModeImport];
documentPicker.delegate = self;
documentPicker.allowsMultipleSelection = FALSE;
documentPicker.popoverPresentationController.barButtonItem = self.selectFilesButton;
[self presentViewController:documentPicker animated:TRUE completion:nil];
}
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray <NSURL *>*)urls {
NSLog(#"picked URLs %#", urls);
// selecting multiple documents is cool, but requires iOS 11
for (NSURL *documentURL in urls) {
//get file details
NSDictionary *attr = [documentURL resourceValuesForKeys:#[NSURLFileSizeKey,NSURLCreationDateKey] error:nil];
NSLog(#"object: %#", attr);
NSNumber *fileSize = [attr valueForKey:NSURLFileSizeKey];
NSDate *dateFileCreated = [attr valueForKey:NSURLCreationDateKey];
NSDateFormatter *storageDateFormat = [[NSDateFormatter alloc] init];
[storageDateFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *createdDateString = [storageDateFormat stringFromDate:dateFileCreated];
MMfile *fileObj = [[MMfile alloc]init];
fileObj.fileName = documentURL.lastPathComponent;
fileObj.meetingID = _meetingID;
fileObj.fileSize = fileSize;
fileObj.fileCreateDate = createdDateString;
//move file to new directory
fileObj.filePath = [self movefile:documentURL.lastPathComponent sourceFilePath:documentURL.path directory:#"fileAttachments"];
//save file details
[self.meetingModel saveFile:fileObj];
//refresh array and reload table
self.fileArray = [self.meetingModel getFiles:self.meetingID];
[self.tableView reloadData];
}
}
- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
NSLog(#"cancelled");
}
-(NSString *)movefile:(NSString *)filename sourceFilePath:(NSString *)sourcePath directory:(NSString *)directoryName{
// Move file from tmp Inbox to the destination directory
BOOL isDir;
NSError *error;
NSFileManager *fileManager= [NSFileManager defaultManager];
//get directory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString* directoryPath;
if (paths>0) {
NSString *documentsDirectory = [paths objectAtIndex:0];
directoryPath = [NSString stringWithFormat:#"%#/%#",documentsDirectory,directoryName];
}
if(![fileManager fileExistsAtPath:directoryPath isDirectory:&isDir])
if(![fileManager createDirectoryAtPath:directoryPath withIntermediateDirectories:NO attributes:nil error:NULL])
NSLog(#"Error: Create folder failed %#", directoryPath);
NSString *destinationPath = [NSString stringWithFormat:#"%#/%#",directoryPath,filename];;
BOOL success = [fileManager moveItemAtPath:sourcePath toPath:destinationPath error:&error];
if (success) {
NSLog(#"moved file");
}else{
NSLog(#"error %#",error.description);
}
return destinationPath;
}
Found the issue. When the project is rebuilt and downloaded to the iPad the AppID changes, and as the documents path includes the AppID, so the documents path changes. Key is not to save the file path, only the file name and rebuild the path each instance. After having found the issue, I now see other similar posts I didn't find earlier. Also see Document directory path change when rebuild application

Email attachment doesn't work as file hasn't finished saving?

I have a function which saves the data extracted from a local SQLite DB to a .CSV file.
My problem is that this function also triggers another which attaches the file to an email and sends it. As the file has not yet finished saving the attachment is sent as an empty file.
Is there anyway I can check if the file has finished saving before attaching it to the email? Please see my function below:
// When the tick is visible within the animation...
// Play the bellToneSound.
AudioServicesPlaySystemSound(bellToneSound);
// Creates a temporary GPS object that we will use to save our database as a .CSV file.
GPS *saveGPS = [[GPS alloc] init];
// Finds the phone's documents directory and creates a file path in order create a new file/folder there.
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/Jobs"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"/Jobs/%#.csv", proposalNumber]];
// Creates our new file, with a name matching "jobNo.csv" overrites old one if it already exists.
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
// Creates a file handler which will allow us to write to our file.
NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
// Creates and writes the first line to our CSV file, which tells the program reading it what the column titles are.
NSString *csvTitleString =#"Source/Monitor, Latitude, Longitude";
[myHandle writeData:[csvTitleString dataUsingEncoding:NSUTF8StringEncoding]];
// Creates initializes another string object which will hold each line we want to write.
NSString *csvString = [[NSString alloc] init];
// Declares an array and fills it with all GPS objects found in our Database.
NSArray *allGPS = [[NSArray alloc]initWithArray:[database getAll]];
// While the current index value is less than the length of the array write the GPS values into our file then take a new line.
for(int i=0;i<(allGPS.count);i++){
saveGPS = [allGPS objectAtIndex:i];
csvString = [NSString stringWithFormat:#"\n %# %d, %#, %#", [saveGPS sourceMonitor], [[saveGPS positionNo] intValue], [saveGPS latitude], [saveGPS longitude]];
[myHandle seekToEndOfFile];
[myHandle writeData:[csvString dataUsingEncoding:NSUTF8StringEncoding]];
}
}
UPDATE
Here is the code you asked for.
NSString *docsDir;
NSString *realpath;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
realpath=[[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent: [NSString stringWithFormat:#"/Jobs/temp.csv"]]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: realpath ] == YES)
{
[self checkIfSaved];
}
else
{
NSLog(#"file found");
// Checks if the device can send email.
if([MFMailComposeViewController canSendMail]){
// Sets the subject to data from (our current proposal number).
[mail setSubject:[NSString stringWithFormat:#"Data from %#", proposalNumber]];
[mail setMessageBody:#"Please see the attached .CSV file." isHTML:NO];
// Finds the .CSV file we just saved, and attaches it to the email.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"/Jobs/%#.csv", proposalNumber]];
NSData *attachment = [NSData dataWithContentsOfFile:[NSString stringWithFormat:#"%#", filePath]];
[mail addAttachmentData:attachment mimeType:#"text/csv" fileName:[NSString stringWithFormat:#"%#",proposalNumber]];
// Opens up the email screen.
[self presentViewController:mail animated:YES completion:NULL];
}
else
{
// Tells the user that there device cannot send email.
NSLog(#"This device cannot send email");
// Creates a popup window to inform the user that their location wasn't updates.
UIAlertController* alert = [UIAlertController alertControllerWithTitle:#"Error"
message:#"Unable to send email. Have you set up a mail account on this device?"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* dismissAction = [UIAlertAction actionWithTitle:#"Dismiss" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {}];
alert.view.tintColor = [UIColor orangeColor];
[alert addAction:dismissAction];
[self presentViewController:alert animated:YES completion:nil];
}
}
You need to arrange your code so that the email part doesn't start until after the file has been completely saved. There are a number of ways to do that:
polling: You can keep checking the status of the file until you find that the operation is complete. Sometimes polling is unavoidable, but it's generally the worst option. Don't go this route.
completion routine: The file saving method could take a parameter that is a block of code to execute when the saving is done. This is very common, and you'll see it all over the place in the various iOS frameworks. For example, NSURLSession has a -dataTaskWithURL:completionHandler: method. When the requested data has been loaded, the completion handler is called.
serial execution: Put your file-saving code in one block and your mail sending code in another block. Then you can use NSOperationQueue or use Grand Central Dispatch directly to schedule both blocks in a serial queue, so that the second block won't start until the first one is finished.
Both the completion routine approach and the serial execution approach are reasonable ways to ensure that you don't start the e-mail process until the file is saved, so pick whichever seems easiest to you.

Format contents of NSMutableArray for .csv file

I have a picture slideshow app which allows the user to rate 3 images. The ratings get stored in a NSMutableArray called rated like this:
2014-01-06 07:10:23.040 SlideShowSurvey[50425:70b] (
1, <-- Rating for Picture 1
2, <-- Rating for Picture 2
3 <-- Rating for Picture 3
)
This is then saved to a .csv file using the following code:
-(void)saveRatings
{
NSString *picRatings = [NSString stringWithFormat:#"%#, \n",self.rated];
// Find documents directory
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *survey = [docPath stringByAppendingPathComponent:#"pictureRatings.csv"];
// Create new file if none exists
if (![[NSFileManager defaultManager] fileExistsAtPath:survey])
{
[[NSFileManager defaultManager] createFileAtPath:survey contents:nil attributes:nil];
}
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:survey];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[picRatings dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
}
I can then display the results of the .csv file to a UITextView, though it displays it exactly how the array is structured. For example, multiple results display as:
(
1,
2,
3
),
(
1,
2,
3
),
(
1,
2,
3
)
Is there a way I am able to format the array so that it is saved as 1,2,3? And would I be able to add a column header like Picture 1, Picture 2, Picture 3? For example, I would like to display results on the UITextView something like:
Picture 1, Picture 2, Picture 3
1,2,3
1,2,3
1,2,3
I've tried searching but can't seem to find this answer. Any help is appreciated! Thanks.
Edit: I have solved this thanks to jrturton's solution, using the following code:
// Set column titles for .csv
NSArray *columnTitleArray = #[#"Picture 1", #"Picture 2", #"Picture 3"];
NSString *columnTitle = [columnTitleArray componentsJoinedByString:#","];
NSString *columnTitleToWrite = [columnTitle stringByAppendingString:#"\n"];
// Separate ratings into cells
NSString *picRatings = [rated componentsJoinedByString:#","];
NSString *picRatingsToWrite = [picRatings stringByAppendingString:#"\n"];
// Find documents directory
..
Then adding this to the method to make sure column headers are only set when a new file is created:
// Create new file if none exists
if (![[NSFileManager defaultManager] fileExistsAtPath:survey])
{
[[NSFileManager defaultManager] createFileAtPath:survey contents:nil attributes:nil];
// Set title for new file
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:survey];
[fileHandle writeData:[columnTitleToWrite dataUsingEncoding:NSUTF8StringEncoding]];
}
..
Here is a much easier way:
NSMutableString *csv = [NSMutableString string];
NSString *label = ...;
[csv appendFormat:#"%#,\n", label];
NSNumber *keyNum = ...;
[csv appendFormat:#"%d,%d\n", [keyNum intValue], [countNum intValue]];
NSString *filename = #"counts.csv";
NSError *error;
[csv writeToFile:filename atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSMutableString *csv = [NSMutableString string];
NSString *label = #"\n";
[csv appendFormat:#",", label];
NSString *picRatings = [rated componentsJoinedByString:csv];
I'm not sure what you expect appendFormat to be doing in the above code, this will probably be raising a warning since label is not used. You don't need a mutable string in this case either.
To get the contents of an array separated by commas, do this:
NSString *picRatings = [rated componentsJoinedByString:#","];
You also need to add a new line to the end of this string, so you'd want:
NSString *picRatingsToWrite = [picRatings stringByAppendingString:#"\n"];
Write this string to your file and you should be fine.
use this parser and get the data into array and look how you can use data into UITabelViewCell https://github.com/davedelong/CHCSVParser

CSV to NSString to NSData with Hebrew text issue

I'm creating a CSV file from CoreData using CHCSVWriter, so far so good and the file is creating perfectly. My problem is when i'm trying to send the CSV file that i've created i'm running in some issues, I open the CSV file with Excel and instead of Hebrew text I see gibberish.
While using NSLog to print the result of the CSV string, I see the Hebrew just fine. Even after converting it from NSString to NSData and back again.
This is what I get:
יוסי צפר
This is my code:
- (void)createCSV
{
CHCSVWriter *writer = [[CHCSVWriter alloc] initForWritingToCSVFile:[self csvFilePath]];
for (EWDBUsers *user in self.users)
{
[writer writeField:user.name];
[writer writeField:user.company];
[writer writeField:user.email];
[writer writeField:user.telephone];
[writer finishLine];
}
[writer closeStream];
}
- (NSString*)csvFilePath
{
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filename = #"users.csv";
return [documentsDirectory stringByAppendingPathComponent:filename];
}
- (void)showMailComposerController
{
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:#"Users List"];
[controller setMessageBody:#"Attachment." isHTML:NO];
NSError *error;
NSString *csvFileString = [NSString stringWithContentsOfFile:[self csvFilePath] encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", csvFileString);
NSData *csv = [csvFileString dataUsingEncoding:[NSString defaultCStringEncoding]];
[controller addAttachmentData:csv mimeType:#"text/cvs" fileName:#"users.csv"];
if (controller) {
[self presentModalViewController:controller animated:YES];
}
} else {
return;
}
}
Can someone please tell me what am I doing wrong?
Thanks in advance.
You're seeing gibberish because you're converting Unicode to ASCII. [csvFileString dataUsingEncoding:[NSString defaultCStringEncoding]] should be [csvFileString dataUsingEncoding:NSUTF8StringEncoding].
Also, mimeType:#"text/cvs" should be mimeType:#"text/csv".
EDIT: The issue seems to be Excel. Opening the received CSV file in TextEdit displays just fine.
My solution is adding BOM chars at start to solve a bug in Excel when try to open CSV files and save the UTF-8 Encoding.
cvsStringFile = [[NSString alloc] initWithFormat:#"\357\273\277%#", cvsStringFile];
NSData *myXLSData = [cvsStringFile dataUsingEncoding:NSUTF8StringEncoding];
[picker addAttachmentData:myXLSData mimeType:#"text/csv;charset=utf-8" fileName:#"Report.csv"];
I suspect, there is an encoding issue. You are sending generated file with an invalid MIME type: text/cvs.
I would use text/plain with an explicit charset parameter, e.g.
text/plain; charset=utf-8
and explicitly encode the csv string into an NSData using that encoding (e.g. NSUTF8StringEncoding).
Edit:
Actually, there is a MIME type text/csv
So, you may also use: text/csv; charset=utf-8

Store and fetch documents in/from app documents folder

Im writing a text editor app and im trying to store a NSString as NSData in files in the documents folder, for example i want to be able to store a file "myText.java".
My code work on the Simulator. However, on the device a file seems to be created, but when I later try to load the data from the files i get nothing.
Do i have to set some project setting to enable the documents directory on device or is my code wrong?
Here is my store code:
-(void) saveFile:(NSString*)file{
if (![file isEqual:#"Empty"]) {
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullFilePath = [documentsDirectory stringByAppendingPathComponent:file];
[[NSFileManager defaultManager] removeItemAtPath: fullFilePath error: nil];
NSLog(#"File: %#", fullFilePath);
//Above LOGS: /var/mobile/Applications/2310F459-282C-4488-AE24-D5795168F85A/Documents/fg
//save content to the documents directory
NSLog(#"Saving: %#", codeView.text);
// Logs the data i want to store
[[codeView.text dataUsingEncoding:NSASCIIStringEncoding] writeToFile:fullFilePath atomically:YES];
}
}
Here is my load file code:
-(void) loadFile:(NSString*)filename{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *file = [documentsDirectory stringByAppendingPathComponent:filename];
if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
NSLog(#"File found");
//Yes the file is found
theDelegate.fileData = [NSData dataWithContentsOfFile:file];
NSLog(#"Data:%#",[[NSString alloc] initWithData:[NSData dataWithContentsOfFile:file] encoding:NSASCIIStringEncoding]);
// On device and simulator data is found
[theDelegate.codeView setText:[[NSString alloc] initWithData:theDelegate.fileData encoding:NSASCIIStringEncoding]];
//codeView does not get updated with the data.
//NSLog([[NSString alloc] initWithData:theDelegate.fileData encoding:NSASCIIStringEncoding]);
[theDelegate setTitle:filename];
[theDelegate setHasOpenFile:YES];
[theDelegate.codeView setEditable:theDelegate.hasOpenFile];
[theDelegate.codeView setNeedsDisplay];
[self setLanguage:filename];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"File error!" message:#"An error occured when trying to load the selected file." delegate:self cancelButtonTitle:#"OK!" otherButtonTitles:nil, nil];
[alert show];
}
}
No, you don't have to enable a setting to use the documents directory. There might or might not be an error with your code, in any case it's hard to read and not very clean (apologies for saying this.)
Try to do everything just once. I took the liberty of rewriting your code a bit, to clean it up. I then tested it with a sample app on my phone, and it works perfectly.
Code rewrite:
-(void) saveFile:(NSString*)filename{
if (![filename isEqual:#"Empty"]) {
NSString *fullFilePath = [self getFullFilePath:filename];
[[NSFileManager defaultManager] removeItemAtPath: fullFilePath error: nil];
NSLog(#"File: %#", fullFilePath);
//save content to the documents directory
NSLog(#"Saving: %#", self.codeView.text);
// Logs the data i want to store
[[self.codeView.text dataUsingEncoding:NSASCIIStringEncoding] writeToFile:fullFilePath atomically:YES];
}
}
The above code is fine, after adding the helper function.
-(void) loadFile:(NSString*)filename{
NSString *fullFilePath = [self getFullFilePath:filename];
if ([[NSFileManager defaultManager] fileExistsAtPath:fullFilePath]) {
NSLog(#"File found");
//Yes the file is found
NSLog(#"Data:%#",[[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fullFilePath] encoding:NSASCIIStringEncoding]);
// On device and simulator data is found
[theDelegate.codeView setText:[[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fullFilePath] encoding:NSASCIIStringEncoding]];
[theDelegate setTitle:filename];
[theDelegate setHasOpenFile:YES];
[theDelegate.codeView setEditable:theDelegate.hasOpenFile];
[theDelegate.codeView setNeedsDisplay];
//[self setLanguage:filename];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"File error!" message:#"An error occured when trying to load the selected file." delegate:self cancelButtonTitle:#"OK!" otherButtonTitles:nil, nil];
[alert show];
}
}
In your old code, there might have been a problem with theDelegate.fileData = [NSData dataWithContentsOfFile:file];, if the reference is weak. Since I presume you'll always have the code in codeView, it seems unnecessary to first store it in a member variable. Also, this might lead to more bugs.
The following is a helper function, so that you don't do the exact same thing in both functions, as it might lead to bugs.
-(NSString*) getFullFilePath:(NSString*)filename {
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullFilePath = [documentsDirectory stringByAppendingPathComponent:filename];
return fullFilePath;
}
Are you taking care that the filenames passed to loadFile: and saveFile: are exactly the same, including capitalization? Mac OS X (and by extension, the iOS simulator) uses case-insensitive filenames, while iOS is case sensitive and treats SomeFile.txt and somefile.txt as two different things.

Resources