简体   繁体   中英

Need to retain, and synthesize NSStrings?

I'm a bit confused as to whether NSStrings should ever be retained and synthesized. I have a NSString value as an instance variable, and am retaining and synthesizing it. But I am assigning it different values such as:

self.value = @"VALUE";
....
self.value = @"DIFFERENT_VALUE";

I'm not actually calling alloc anytime. Do I need to retain and synthesize this variable then?

You can think of on-the-fly strings as autoreleased in terms of how you use them, although in reality they will probably stay around as fixed values... because you are using the accessors they will automatically get copied or retained (however you marked the accessor) and so you do need to release them in dealloc.

As for the need to @synthesize, remember all that is doing for you is actually creating the get/set methods that take the variable and place it in your iVar. So not matter what you either need to @synethsize a property OR create the get/methods yourself - usually far better just to use @sythesize.

You should as you'll never know how you are going to change the use of the code in the future. Change the code to use dynamically created strings, and it will break if don't follow the rules.

Also note that the best practice for NSString is to set it to copy instead of retain. The reason is simple, this prevents the string from being changed under your feet.

See NSString property: copy or retain? for more details.

如果你从来没有分配它们,你通常不需要保留,但如果它们是你对象中的实例变量,它们可能被标记为保留复制,所以在你的对象的dealloc方法中你应该释放这些对象,如果有的话一个值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM