The latter ( NSData * data = [string dataUsingEncoding:NSUTF8StringEncoding] ) is an option that I would recommend.
Why?
Some people will say effectiveness. In this case, using the string instance method to create an NSData object, only one obj-c message needs to be sent to Apple code, which is highly optimized. In another case (creating a new NSData object using the class method), you will need two messages for your string object and 1 sending a message to the NSData class object.
However, the runtime is unlikely to change much, and even if it does, the encoding cost will be based on the length of the string, and not on what methods you use to create the NSData object.
I would say that the real reason you want to use the instance method in NSString is semantics and clarity.
Let's look at the pseudo-English translation of these options:
[string DataUsingEncoding:NSUTF8StringEncoding] : Hey string, I want you to give me a copy of NSData using UTF8 encoding. Well, thanks, put it right there - no, not on the mat.[NSData dataWithBytes:[req_string UTF8String] length:[req_string length]] : String! Give me all your UTF8 bytes. yeah oh i need your length too Sec. NSData, go here, I need you to take this thing, and go to my doorstep and turn it into data objects, strings, expectations, gently! Don't break anything "
What seems more understandable to you?
source share