The easiest way to write NSData to a file - file

NSData *data;
data = [self fillInSomeStrangeBytes];
My question is now how I can write this data on the easiest way to an file.
(I've already an NSURL file://localhost/Users/Coding/Library/Application%20Support/App/file.strangebytes)

NSData has a method called writeToURL:atomically: that does exactly what you want to do. Look in the documentation for NSData to see how to use it.

Notice that writing NSData into a file is an IO operation that may block the main thread. Especially if the data object is large.
Therefore it is advised to perform this on a background thread, the easiest way would be to use GCD as follows:
// Use GCD's background queue
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// Generate the file path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"yourfilename.dat"];
// Save it into file system
[data writeToFile:dataPath atomically:YES];
});

writeToURL:atomically: or writeToFile:atomically: if you have a filename instead of a URL.

You also have writeToFile:options:error: or writeToURL:options:error: which can report error codes in case the saving of the NSData failed for any reason. For example:
NSError *error;
NSURL *folder = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error];
if (!folder) {
NSLog(#"%s: %#", __FUNCTION__, error); // handle error however you would like
return;
}
NSURL *fileURL = [folder URLByAppendingPathComponent:filename];
BOOL success = [data writeToURL:fileURL options:NSDataWritingAtomic error:&error];
if (!success) {
NSLog(#"%s: %#", __FUNCTION__, error); // handle error however you would like
return;
}

The easiest way, if you want to do this a few times manually instead of coding, is to only use your mouse:
Put a breakpoint one line after your NSdata are fulfilled.
Hold your mouse over your NSData variable, click on the Eye button, and then export.
After that chose the storage details (name/extension/location of the file).
Click on "Save" and you are done!

Related

How to access a field in struct

I have the following code in my Xcode project:
- (BOOL)getIP;
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://httpbin.org/ip"]];
request.HTTPMethod = #"GET";
[request setValue:#"TestValue" forHTTPHeaderField:#"Test"];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"getIP returns = %#", dict);
return NO;
}
When I set a breakpoint in lldb using the "breakpoint set -b CFURLRequestSetHTTPHeaderFieldValue" command and trigger the getIP method, the code stops as expected.Then I intput the "po $x0
" lldb command and it prints "<CFMutableURLRequest 0x1741bff00 [0x1a7808bb8]> {url = http://httpbin.org/ip, cs = 0x0}".
What I want to know is: 1.how to access the url filed in struct CFMutableURLRequest; 2.how to get the definition of struct CFMutableURLRequest.
Thanks in advance!
The po command shows you the result of the description message sent to the object. There's no guarantee that the text printed by descriptionis telling you about particular ivars in the object, it's just some free-form text that the class author can fill with whatever she best thinks describes the object. The fact that it says "url =" doesn't mean there actually is an ivar called url.
You can use the p or expr commands to print the contents of the object (at least so far as that is available to the debugger.) Since this is a pointer, you'll want to do:
(lldb) p *request
In this case, it looks like these are opaque objects - the debug information doesn't say how they are laid out. So the debugger can't really help you look into the object directly.

Objective-C - How to write an array to a file?

I have a text file that I can scan (NSScanner) and tag. The results are stored in an array. The structure is two strings, one for english and one for greek.
I want to write an output file that maintains the array structure. I presume I can create a plist file for this purpose.
However, I'm stuck and need help to create this file.
I have a test whether the file was created, but I get this result:
outgoingWords.count: 442
2014-08-12 17:54:17.369 MyScanner[97350:2681695] *** Assertion failure in -[ViewController checkArray], /Users/david/Desktop/Word Scanning/MyScanner/MyScanner/ViewController.m:98
2014-08-12 17:54:17.373 MyScanner[97350:2681695] Failed to set (contentViewController) user defined inspected property on (NSWindow): writeToFile failed
The code I'm using so far is as follows:
-(void)checkArray {
//do stuff to verify the array
long i = outgoingWords.count;
NSString *tempString = [NSString stringWithFormat:#"%li", i];
NSLog(#"outgoingWords.count: %#", tempString); //442
NSArray *tempArray2 = [outgoingWords copy];
NSString *path = [[NSBundle mainBundle] pathForResource:#"/Users/David/Desktop/alfa2" ofType:#"plist"];
BOOL success = [tempArray2 writeToFile:path atomically:YES];
NSAssert(success, #"writeToFile failed");
}
Could someone either identify what I'm missing, or point me to an existing answer I can use (I've looked)..
Many thanks..
edit. I've also tried the approach in this SO question. But get the same result.
NSString *path = [[NSBundle mainBundle] pathForResource:#"/Users/David/Desktop/alfa2" ofType:#"plist"];
NSString *error;
NSData *data = [NSPropertyListSerialization dataFromPropertyList:tempArray2 format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error];
BOOL success = [NSKeyedArchiver archiveRootObject:data toFile:path];
NSAssert(success, #"archiveRootObject failed");
Problem is that you are writing to the bundle, which is not allowed. You should write to a path in your document or other directory, for example:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePath = [documentsDirectory stringByAppendingPathComponent:#"FileName.xxx"];
[data writeToFile:filePath atomically:NO];

Adding data given by the user to an array - Objective-C

I'm trying to create a Mac OS X app where there are some default sound and the user can add others if he wants. I'm loading the sounds to an array in -awakeFromNib :
for (NSString *str in [PreferencesController beats]) {
resourcePath = [[NSBundle mainBundle] pathForSoundResource:str];
beat = [[NSSound alloc] initWithContentsOfFile:resourcePath byReference:YES];
[beat setLoops:YES];
[beat setName:str];
[beatsArray addObject:beat];
}
Everything works fine until the app tries to add to the array a sound added by the user. It says : *** -[NSURL initFileURLWithPath:]: nil string parameter. I'm guessing that it can't find the URL of the file but I'm copying the file to the app's directory when the user selects it by the following code :
if ( [openDlg runModalForTypes:[NSArray arrayWithObjects:#"aif",#"aiff",#"mp3",#"wav",#"m4a",nil]] == NSOKButton)
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dataPath = [[NSBundle mainBundle] bundlePath];
NSLog(#"Datapath is %#", dataPath);
NSLog(#"Selected Files : %#",[[openDlg URLs] objectAtIndex:0]);
[fileManager copyItemAtURL: [[openDlg URLs] objectAtIndex:0] toURL: [NSURL fileURLWithPath: [[NSBundle mainBundle] bundlePath]] error:&error];
NSLog(#"File copied");
NSMutableArray *newArray = [[NSMutableArray alloc] initWithArray:[PreferencesController beats]];
NSString *fileName = [[[openDlg URL] path] lastPathComponent];
NSArray *fileNameArray = [fileName componentsSeparatedByString:#"."];
[newArray addObject:[fileNameArray objectAtIndex:0]];
NSLog(#"%#",newArray);
[PreferencesController setBeats:newArray];
[self awakeFromNib];
[_tableView reloadData];
}
What's wrong with this code?
Looks like you're trying to copy a file to a folder because you're just using the bundle path as the destination URL. The destination URL needs to specify the full path including the destination file name.
Try logging the error when the file is copied:
NSLog(#"File copied with error: %#", error);
This line contains the error:
[fileManager copyItemAtURL: [[openDlg URLs] objectAtIndex:0] toURL: [NSURL fileURLWithPath: [[NSBundle mainBundle] bundlePath]] error:&error];
Specifically, the problem is that the destination URL is a folder:
[[NSBundle mainBundle] bundlePath]
It should be something like:
[[[NSBundle mainBundle] bundlePath] stringByAppendingString:[[[[openDlg URLs] objectAtIndex:0] path] lastPathComponent];
Then, once you have it working, as #Abizern says in the comments, saving to the bundle is a bad idea (it's part of the app).
Once you have it working, you should choose a better location to save the sounds to (like a support document folder for the app, Programmatically get path to Application Support folder)

Best way to populate this array using .txt file?

I'm looking to make SEVERAL arrays populated with words. Eventually I want to be able to just pull a random word from the array and display it (I've mastered that). What I'm wondering is what is the best way to populate this array. Should I just type in:
[NSArray arrayWithObjects:#"word1",#"word2",#"word3",#"word4",#"word5",nil]
or is there a better way where the words are stored in a .txt file and I can just have a loop add each word in the text file to the Array?
I'm looking at filling the arrays with 100's of words. Any and all help is appreciated :D.
UPDATE
After doing some research I found this here. It seems to be exactly what I wanted. The only thing is it gives me a warning
'stringWithContentsOfFile' is deprecated
I know the full NSString method is:
stringWithContentsOfFile:(NSString *) encoding:(NSStringEncoding) error:(NSError **)
But I don't know what to put for encoding (and I'm assuming I can just put 'nil' for NSError). Other than that it works like a charm. I might consider switching from paths to urls. Here is the code that I found:
- (NSArray *) readFile:(NSString *) path {
NSString *file = [NSString stringWithContentsOfFile:path];
NSMutableArray *dict = [[NSMutableArray alloc] init];
NSCharacterSet *cs = [NSCharacterSet newlineCharacterSet];
NSScanner *scanner = [NSScanner scannerWithString:file];
NSString *line;
while(![scanner isAtEnd]) {
if([scanner scanUpToCharactersFromSet:cs intoString:&line]) {
NSString *copy = [NSString stringWithString:line];
[dict addObject:copy];
}
}
NSArray *newArray = [[NSArray alloc] initWithArray:dict];
return newArray;
}
You can probably use NSUTF8StringEncoding for the encoding parameter (depending on how you created the file, but this is the most common).
Instead of using NSScanner, you can also simply split the string into lines with the componentsSeparatedByString: method. This reduces your method to just these two lines:
NSString *file = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
return [file componentsSeparatedByString:#"\n"];
Btw, you shouldn't name an array variable "dict", this would imply that it's an NS(Mutable)Dictionary.
The less code way to get in a list of words would be:
NSString *path = [[NSBundle mainBundle] pathForResource:#"Words" ofType:#"plist"];
NSArray *words = [[NSArray alloc] initWithContentsOfFile:path];
Then you just have to create a plist that has all the words in it with the root object as an array.
In the method you have above the encoding you are looking for is NSUTF8StringEncoding and you actually should pass an NSError by reference, if something goes wrong the error could be useful:
NSError *anError = nil;
NSString *file = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&anError];

Saving files in cocoa

I'm sure this is a really easy to answer question but I'm still new to cocoa. I need to save my applications data. The app has 4 text fields and each field needs to be saved into one file. Then when you open the file it needs to know what goes in what field. I'm really stuck with this. Also, I do know how to use the save panel.
A convenient way would be to use PLists:
NSDictionary *arr = [NSDictionary dictionaryWithObjectsAndKeys:
string1, #"Field1", string2, #"Field2", nil];
NSData *data = [NSPropertyListSerialization dataFromPropertyList:arr
format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];
NSSavePanel *panel = [NSSavePanel savePanel];
NSInteger ret = [panel runModal];
if (ret == NSFileHandlingPanelOKButton) {
[data writeToURL:[panel URL] atomically:YES];
}
For deserialization:
NSData *data = [NSData dataWithContentsOfURL:urlOfFile];
NSDictionary *dict = [NSPropertyListSerialization propertyListFromData:data
mutabilityOption:NSPropertyListImmutable
format:nil errorDescription:nil];
NSString *string1 = [dict objectForKey:#"Field1"];
// ... etc.

Resources