Fast line string recoding in iOS?

I have a URL string with the variables added to the end, for example:

.../create?title=My Apartment 

I would like to avoid any invalid characters (e.g. space), but when I try to do this, I will crash both in the simulator and on my device (iOS 8.0) using the following:

 NSLog("Item1: \(item)") NSLog("Item2: \(item.title)") if let scrubbed = item.title.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet()) { NSLog("Scrubbed: \(scrubbed)") } else { NSLog("Nope!") } 

What I see on the simulator is:

 2014-09-24 16:59:19.120 MyApp[16406:171349] Item1: MyApp.PostItem 2014-09-24 16:59:19.121 MyApp[16406:171349] Item2: My Apartment 2014-09-24 16:59:19.125 MyApp[16406:171349] Scrubbed: My 0X0P+0partment 

Note the weirdness of this erased line. Some time later, it fails, complaining of a poorly constructed NSURL object, which is not surprising.

When I run this on my device , I crash with EXC_BAD_ACCESS in NSLog() , which is trying to print Scrubbed:

 2014-09-24 17:04:37.378 MyApp[4346:2048259] Item1: MyApp.PostItem 2014-09-24 17:04:37.379 MyApp[4346:2048259] Item2: My Apartment (lldb) po scrubbed error: <EXPR>:1:1: error: non-nominal type '$__lldb_context' cannot be extended extension $__lldb_context { ^ <EXPR>:11:5: error: 'PostManager.Type' does not have a member named '$__lldb_wrapped_expr_3' $__lldb_injected_self.$__lldb_wrapped_expr_3( ^ ~~~~~~~~~~~~~~~~~~~~~~ (lldb) 

How can I understand what is going on here? I would expect to see Nope! printed on the console before it is smashed like this. The String value in the model object is provided using a UITextField .

Edit: I was able to get some NSData result from a previously cleared value:

 NSLog("Data: \(item.title.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false))") ... 2014-09-24 17:18:43.620 MyApp[4367:2051348] Data: Optional(<4d792041 70617274 6d656e74>) 

Edit 2: I can confirm this crashes in Xcode and passes on the playground. This seems to be a mistake, but where? Xcode? Compiler? Play time

Edit 3: This error only occurs when trying to print the value of a variable using NSLog() . If I completely avoid this and just use the variable, everyone will be happy.

+6
source share
1 answer

It seems like escaping with NSCharacterSet.URLHostAllowedCharacterSet() creates a weird unicode string, which causes the NSLog to crash if this string is used as the first parameter.

There are several ways to avoid this, and you should definitely use them:

  • As far as you use this query in the URL, you should definitely use another characher set - NSCharacterSet.URLQueryAllowedCharacterSet() .

  • Use print/println

  • Pass scrubbed to NSLog as an NSLog("Scrubbed: %@", scrubbed) parameter NSLog("Scrubbed: %@", scrubbed)

Any of these "workarounds" solves the problem.

+5
source

Source: https://habr.com/ru/post/975803/


All Articles