How to access a field in struct - lldb

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.

Related

Unwrapping Plist and finding object

Getting hugely frustrated trying to translate objective c to swift. I have the following code that works for objective c.
NSMutableArray *path = [NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Sequence List" ofType:#"plist"]];
//Shuffle the array of questions
numberSequenceList = [self shuffleArray:path];
currentQuestion = currentQuestion + 1;
if (Round==1) {
//Take first object in shuffled array as the first question
NSMutableArray *firstQuestion = [[NSMutableArray alloc] initWithArray:[numberSequenceList objectAtIndex:0]];
//Find question and populate text view
NSString *string = [firstQuestion objectAtIndex:0];
self.lblNumber.text = string;
//Find and store the answer
NSString *findAnswer = [firstQuestion objectAtIndex:1];
Answer = [findAnswer intValue];
}
But I can't seem to get this to work in swift. I can pull out the contents of the plist using
var path = NSBundle.mainBundle().pathForResource("Sequence List", ofType: "plist")
But I can't see that there is an equivalent to objectAtIndex in swift. If I try the following I get an error message advising "string does not have a member named subscript", which apparently means I need to unwrap path.
let firstQuestion = path[0]
The methods you are calling, like NSBundle.mainBundle().pathForResource, return optionals, because they might fail. In Objective-C, that failure is indicated by a nil, whereas Swift uses optionals.
So in your example:
var path = NSBundle.mainBundle().pathForResource("Sequence List", ofType: "plist")
path is of type Optional<String> (or String?) and not of type String. Optional<String> doesn’t have a subscript method (i.e. doesn’t support [ ]). To use the string within, you have to check if the optional contains a value (i.e. the call to pathForResource was successful):
// the if let syntax checks if the optional contains a valid
if let path = NSBundle.mainBundle().pathForResource("Sequence List", ofType: "plist”) {
// use path, which will now be of type String
}
else {
// deal with pathForResource failing
}
You can read more about optionals in introduction of the Swift book.
You haven't translated the entire first line from Objective-C. You are missing the call to NSMutableArray which creates the array from the contents of the file. The original code is confusing because it calls the contents of the file path when it is really questions. Try this:
if let path = NSBundle.mainBundle().pathForResource("Sequence List", ofType: "plist") {
let questions = NSMutableArray(contentsOfFile: path)
//Shuffle the array of questions
numberSequenceList = self.shuffleArray(questions)
currentQuestion = currentQuestion + 1
if Round == 1 {
//Take first object in shuffled array as the first question
let firstQuestion = numberSequenceList[0] as NSArray
//Find question and populate text view
let string = firstQuestion[0] as NSString
self.lblNumber.text = string
//Find and store the answer
let findAnswer = firstQuestion[1] as NSString
Answer = findAnswer.intValue
}
}

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];

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.

The easiest way to write NSData to a 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!

Resources