Printing NSData using NSLog

后端 未结 5 960
孤城傲影
孤城傲影 2020-12-07 18:26

How can I print the contents of an NSData object using NSLog:

-(void) post:(NSString*) msg to:(NSString*) link{
    NSString *myRequestString = [NSString str         


        
5条回答
  •  青春惊慌失措
    2020-12-07 19:23

    I somewhat often want to see what the NSData actually represent. Usually it's some sort of text, which makes hex a bit inconvenient. Therefore I usually write this snippet in the JavaScript console in my web browser, works pretty fast and can be modified easily if some continued processing would be wanted.

    1. Copy/paste the following script into your browser console (right click here -> Inspect element), hit enter

      (function nsDataHexToString() {
          var str = prompt("Paste the hex string here:", "ié. 48656c6c 6f207468 657265...")
          var chs = str.replace(/[^A-F0-9]/ig,"").split("")
          var res = ""
          var cnt = 2
          for (var i = 0; i+cnt-1
    2. Run your swift/obj-c code, put in a breakpoint and inspect your NSData object

      let sample = "Hello there"
      let data = sample.dataUsingEncoding(NSUTF8StringEncoding)
      // Put breakpoint here, hover over "data", and press the eye/i
      
    3. Copy the hex (something like <48656c6c 6f207468 657265>) and paste into the browser prompt

    4. The console will then show a string: "Hello there"

    Most recently, it was to inspect the output from NSAttributedString.dataFromRange, the rtfd was using a bit different encoding, but I got what I needed :) Also useful for some json conversion issues, etc.

    Good luck :)

提交回复
热议问题