优点和缺点是使用[NSString stringWithString:@“some string”]对比@“一些字符串” [英] Pros and Cons of using [NSString stringWithString:@"some string"] versus @"some string"

查看:238
本文介绍了优点和缺点是使用[NSString stringWithString:@“some string”]对比@“一些字符串”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较以下简单分配:

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

self.textField.text = @some string;
self.textField.text = [NSString stringWithString:@some string];
self.textField.text = [NSString stringWithFormat:@some string];

其中 textField UITextField text 属性a NSString 。当然所有的工作。我知道最后两个使用参数的差别。




  1. 对于这种类型的赋值,为什么我不应该总是使用第一个赋值?

  2. 比较最后两个, /或这两个的运行时间?为什么我应该使用 stringWithString:


方案


为了做这种分配,我为什么不使用第一个?


始终使用您描述的情况下的第一个。第二和第三种情况可能复制常量字符串,但是UITextField的 text 属性被指定为仍然复制提供的字符串。在创建一个常量字符串的副本没有意义,因此UITextField的 -setText:可以复制该副本。


比较最后两个,对于compile-
和/或这两个的运行时有没有什么区别?为什么要使用stringWithString:at
all if?


我的理解是 stringWithFormat:将始终创建一个新的字符串,而 -stringWithString:可能不会(可能不)上面的hypercrypt的结果在这方面是很有说服力的;如果你想探索更多,你可以尝试一个可变字符串相同的测试。


I want to compare the following simple assignments:

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

self.textField.text = @"some string";
self.textField.text = [NSString stringWithString:@"some string"];
self.textField.text = [NSString stringWithFormat:@"some string"];

Where textField is an UITextField and the text property a NSString. Of course all of them work. I know the difference of the last two when using parameters. But lets say we are only interested in this usage.

QUESTIONS:

  1. For doing this kind of assignment, why shouldn't I always use the first one?
  2. 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?

解决方案

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.

这篇关于优点和缺点是使用[NSString stringWithString:@“some string”]对比@“一些字符串”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆