Pros and Cons of using [NSString stringWithString:@“some string”] versus @“some string”

后端 未结 4 1285
野性不改
野性不改 2020-12-12 02:22

I want to compare the following simple assignments:

...
@property(nonatomic,retain) UITextField *textField;
...

self.textField.text = @\"some string\";
self         


        
4条回答
  •  北海茫月
    2020-12-12 03:20

    For doing this kind of assignment, why shouldn't I always use the first one?

    You should always use the first one in the situation you describe. The second and third cases potentially copy the constant string, but the text property of UITextField is specified as copying the provided string anyway. There's no sense in making a copy of a constant string just so UITextField's -setText: can copy that copy.

    Comparing the last two, is there any difference for the compile- and/or runtime of these two? And why should I use stringWithString: at all if not?

    My understanding is that -stringWithFormat: will always create a new string, while -stringWithString: might not (probably doesn't) for a constant string. hypercrypt's results above are pretty telling in this respect; if you wanted to explore that more, you might try the same test with a mutable string.

提交回复
热议问题