NSString fails, app crashes trying to NSLog the NSError - objective-c

What it says on the tin. All I want to do is save an NSString to a .txt file in my Documents directory so it can be accessed by the user. This is called in applicationWillTerminate:
NSError* err;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"TheFile.txt"];
BOOL success = [[textView text] writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&err];
if (!success) {
NSLog(#"Error: %# %#", err, [err userInfo]);
}
In my case, success comes back as NO, and my app crashes (EXC_BAD_ACCESS) on the NSLog line. Any ideas?

If textView (or [textView text]) is nil, success will be NO but err will be uninitialized. That's the only possible way to crash here.
Try setting NSError* err = nil;

I believe you should be checking the error object, not the success boolean value. After all - that's why you're passing it's address for the write operation.
if (error) {
NSLog(#"Error: %#", err);
}
Also you may want to check that [textView text] does not return nil and if textView isn't nil itself.

Related

Using apples suggested code isnt excluding files from icloud backup

I have an app that has been rejected 3 times due to icloud backup issues. Apple have written back to say that I need to use there bit of code to exclude the files from being backed up. However this isnt working and i am at wits end.
Here is the code i've used
- (BOOL)downloadFile:(NSString *)fileURI targetFolder:(NSString *)targetFolder targetFilename:(NSString *) targetFilename{
#try{
NSError *error = nil;
NSURL *url = [NSURL URLWithString:fileURI];
if(![url setResourceValue:#"YES" forKey:NSURLIsExcludedFromBackupKey error:&error]){
NSLog(#"KCDM: Error excluding %# from backup %#", fileURI, error);
}else{
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingString:targetFolder];
NSError *error = nil;
if(![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&error];
}
NSString *filePath = [NSString stringWithFormat:#"%#/%#%#", documentsDirectory,targetFolder,targetFilename];
return [urlData writeToFile:filePath atomically:YES];
}
}
}
#catch(NSException * e){
NSLog(#"Error download: %#",e);
}
return false;
}
what am i doing wrong?
You try to set NSURLIsExcludedFromBackupKey for the http://-Url you download from the web. That won't work.
You have to set this key-value pair for the actual file that is saved on the device.
Additionally you are not supposed to set this value to the string #"YES", you must use a NSNumber object representing the boolean value YES.
For example:
NSString *filePath = [NSString stringWithFormat:#"%#/%#%#", documentsDirectory,targetFolder,targetFilename];
if ([urlData writeToFile:filePath atomically:YES]) {
// did write correctly
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
if(![fileURL setResourceValue:#YES forKey:NSURLIsExcludedFromBackupKey error:&error]){
NSLog(#"KCDM: Error excluding %# from backup %#", fileURI, error);
return NO;
}
// could set NSURLIsExcludedFromBackupKey
return YES;
}
// could not write to file
return NO;

Renaming an existing file with Obj-C

I've seen this question asked a few times but I have been unable thus far to achieve success using any of the post solutions. What I am trying to do is rename a file in the local storage of an app (also kind of new to Obj-c). I am able to retrieve the old path and create the new path, but what would I have to write in order to actually change the files name?
What I have thus far is:
- (void) setPDFName:(NSString*)name{
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString* initPath = [NSString stringWithFormat:#"%#/%#",[dirPaths objectAtIndex:0], #"newPDF.pdf"];
NSString *newPath = [[NSString stringWithFormat:#"%#/%#",
[initPath stringByDeletingLastPathComponent], name]
stringByAppendingPathExtension:[initPath pathExtension]];
}
NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtPath:initPath toPath:newPath error:&error];
The code is very messy; try this:
- (BOOL)renameFileFrom:(NSString*)oldName to:(NSString *)newName
{
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
NSString *oldPath = [documentDir stringByAppendingPathComponent:oldName];
NSString *newPath = [documentDir stringByAppendingPathComponent:newName];
NSFileManager *fileMan = [NSFileManager defaultManager];
NSError *error = nil;
if (![fileMan moveItemAtPath:oldPath toPath:newPath error:&error])
{
NSLog(#"Failed to move '%#' to '%#': %#", oldPath, newPath, [error localizedDescription]);
return NO;
}
return YES;
}
and call this using:
if (![self renameFileFrom:#"oldName.pdf" to:#"newName.pdf])
{
// Something went wrong
}
Better still, put the renameFileFrom:to: method into a utility class and make it a class method so it can be called from anywhere in your project.

NSApplicationSupportDirectory invalid CFStringRef

I'm trying to store a file in the NSApplicationSupportDirectory, since i have a preloaded folder in my app, which i want to add files to once the app have been initialized. I'm trying to NSLog the content of the file, so i can see if it actually worked. From the debugger, i can see that the content is , which i don't not what means. Anybody?
NSString *document = [NSString stringWithFormat:#"%# %# %# %# %#", description, focus, level, equipment, waterDepth];
//NSLog(#"%#", document);
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *supportDirectory = [paths objectAtIndex:0];
//filename
NSString *filename = [NSString stringWithFormat:#"%#/%#", supportDirectory,[_nameTextField.text stringByAppendingString:#".txt"]];
NSLog(#"%#", supportDirectory);
NSLog(#"%#", filename);
[document writeToFile:filename atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
NSString *content = [[NSString alloc]initWithContentsOfFile:filename usedEncoding:nil error:nil];
NSLog(#"%#", content);
You're not passing a string encoding, you are passing NSStringEncodingConversionAllowLossy which is an option that can affect how encoding conversion happens for certain methods (not the one you're using). You need to pass something like NSUTF8StringEncoding.
When you write or read files, it is highly recommended to use the error parameter and handle the cases where you get an error. Also, this is very useful to help you debug your code.
For example, in your case, you can do like this:
NSError *error = nil;
BOOL success = [document writeToFile:filename atomically:NO encoding:NSStringEncodingConversionAllowLossy error:&error];
if (!success) {
NSLog(#"Could not write file: %#", error);
} else {
NSString *content = [[NSString alloc]initWithContentsOfFile:filename usedEncoding:nil error:&error];
if (!content) {
NSLog(#"Could not read file: %#", error);
}
}
If you get an error that says that The operation couldn’t be completed. No such file or directory, that means that you did not previously create the folder. So you create it before trying to add content to it:
NSString *supportDirectory = [paths objectAtIndex:0];
NSError *error = nil;
BOOL success;
if (![[NSFileManager defaultManager] fileExistsAtPath: supportDirectory]) {
success = [[NSFileManager defaultManager] createDirectoryAtPath:supportDirectory withIntermediateDirectories:YES attributes:nil error:&error];
if (!success) {
NSLog(#"Could not create directory: %#", error);
}
}

Exc_Bad_Access Exception on creating database in Iphone

i receive this exception after calling the following method. And it only comes when app load for the first time. When i again open the app it works fine. Can anyone help?
-(void) createAndCheckDatabase
{
BOOL success;
self.databaseName = #"database.db";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentPaths objectAtIndex:0];
self.databasePath = [[documentDir stringByAppendingPathComponent:self.databaseName]retain];
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:self.databasePath];
if(success) return;
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseName];
NSError *err;
[fileManager copyItemAtPath:databasePathFromApp toPath:self.databasePath error:nil];
if (err) {
// DebugLog(#"%#", [err description]);
}
}
if (err) ... will crash because err is not initialized! and you dont use it in fileManager copyItemAtPath:
EXEC_BAD_ACCESS almost always means either a bug dealing with pointers or C-arrays, or an object was over-releaseed.
The good news is that you should have a stack-trace in the Debugger (if running in Xcode), or a crash log, that shows exactly what went wrong. (How to gather and read crash logs).
"Profiling" your code with the Zombies instrument is the best way to get more information about over-releases.
If you can post a symbolicated stacktrace, we can try and give you a better diagnosis.

Getting the contents of a file in Xcode

In my project I have a plain text file called GAME.js, and I'm trying to get the contents of the file.
[NSString stringWithContentsOfFile:#"GAME.js" encoding:NSUTF8StringEncoding error:nil];
sounds like it should work, but it's just returning an empty string.
Please help me fix this.
Put GAME.js into the Resources folder in your Xcode project and use the following code to get the contents of the file.
NSError *error = nil;
NSString* path = [[NSBundle mainBundle] pathForResource:#"GAME" ofType:#"js"];
NSString* gameFileContents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
If you pass in a NSError it will tell you exactly what the problem is:
NSError *error = nil;
NSString *myString = [NSString stringWithContentsOfFile:#"GAME.js" encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
} else {
NSLog(#"%#", myString);
}
NSError Documentation
Also, check to see if it is in your documents directory which can be accessed with NSSearchPathForDirectoriesInDomains:
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fullPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"GAME.js"];
NSString *myString = [NSString stringWithContentsOfFile:fullPath encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"%# - %#", [error localizedDescription], [error localizedFailureReason]);
} else {
NSLog(#"%#", myString);
}