开发者

Objective-C String Differences

开发者 https://www.devze.com 2023-01-15 07:07 出处:网络
What\'s the difference between NSString *myString = @\"Johnny Appleseed\" versus NSString *myString = [NSSt开发者_运维技巧ring stringWithString: @\"Johnny Appleseed\"]?

What's the difference between NSString *myString = @"Johnny Appleseed" versus NSString *myString = [NSSt开发者_运维技巧ring stringWithString: @"Johnny Appleseed"]?

Where's a good case to use either one?


The other answers here are correct. A case where you would use +stringWithString: is to obtain an immutable copy of a string which might be mutable.


In the first case, you are getting a pointer to a constant NSString. As long as your program runs, myString will be a valid pointer. In the second, you are creating an autoreleased NSString object with a constant string as a template. In that case, myString won't point to a real object anymore after the current run loop ends.

Edit: As many people have noted, the normal implementation of stringWithString: just returns a pointer to the constant string, so under normal circumstances, your two examples are exactly the same. There is a bit of a subtle difference in that Objective-C allows methods of a class to be replaced using categories and allows whole classes to be replaced with class_poseAs. In those cases, you might run into a non-default implementation of stringWithString:, which may have different semantics than you expect it to. Just because it happens to be that the default implementation does the same thing as a simple assignment doesn't mean that you should rely on subtle implementation-specific behaviour in your program - use the right case for the particular job you're trying to do.


Other than syntax and a very very minor difference in performance, nothing. The both produce the exact same pointer to the exact same object.

Use the first example. It's easier to read.


In practice, nothing. You wouldn't ever use the second form, really, unless you had some special reason to. And I can't think of any right now.

(See Carl's answer for the technical difference.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号