NSString 的copy和retain

2023-11-02 22:21
文章标签 nsstring copy retain

本文主要是介绍NSString 的copy和retain,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!


stackoverflow上的说法是这样的。http://stackoverflow.com/questions/387959/nsstring-property-copy-or-retain


For attributes whose type is an immutable value class that conforms to the NSCopying protocol, you almost always should specify copy in your @property declaration. Specifying retain is something you almost never want in such a situation.

Here's why you want to do that:

NSMutableString *someName = [NSMutableString stringWithString:@"Chris"];Person *p = [[[Person alloc] init] autorelease];
p.name = someName;[someName setString:@"Debajit"];

The current value of the Person.name property will be different depending on whether the property is declared retain or copy — it will be @"Debajit" if the property is marked retain, but@"Chris" if the property is marked copy.

Since in almost all cases you want to prevent mutating an object's attributes behind its back, you should mark the properties representing them copy. (And if you write the setter yourself instead of using@synthesize you should remember to actually use copy instead of retain in it.)


规范上NSString做属性都是写成copy的,理论上应该是复制了字符串而不是单纯的增加引用计数,

其实问题只会出现在把NSMutableString赋值给NSString的时候。如果对实际类型就是NSString的对象用了copy,那其实就是retain,你可以通过观察引用计数来发现,而且就语义上来说也完全没有问题,同时也避免了不需要的字符串拷贝的消耗

 

Objective-c代码   收藏代码
  1. @interface Demo : NSObject  
  2. {  
  3.     NSString *retainString;  
  4.     NSString *copyString;  
  5. }  
  6.   
  7. @property (nonatomic, retain)NSString *retainString;  
  8. @property (nonatomic, copy)NSString *copyString;  
  9. @end  
  10.   
  11. @implementation Demo  
  12. @synthesize retainString;  
  13. @synthesize copyString;  
  14. -(void)dealloc  
  15. {  
  16.     [retainString release];  
  17.     [copyString release];  
  18.     [super dealloc];  
  19. }  
  20.   
  21. @end  
  22.   
  23. Demo *o = [[Demo alloc] init];  
  24. NSMutableString *s1 = [[NSMutableString alloc] initWithCapacity:100];  
  25. [s1 setString:@"changeme"];  
  26. o.retainString = s1;  
  27. o.copyString = s1;  
  28. NSLog(@"retain string is %@", o.retainString);  
  29. NSLog(@"copy string is %@", o.copyString);  
  30. [s1 setString:@"whetherchanged?"];  
  31. NSLog(@"retain string is %@", o.retainString);  
  32. NSLog(@"copy string is %@", o.copyString);  

 这样就可以看出,当使用retain方式的时候,NSMutableString的内容变化时,语义上应该不可变的NSString也变化了,而用copy则是始终保持赋值时的内容。

 

1。对NSString应用retain,效率无疑是最好的

2。用copy最安全,因为NSString 为 NSMutableString 的基类,如果将NSMutableString 以retain的形式赋值给NSString后,后续修改NSMutableString会导致NSString内容的变化,这通常不是我们希望的,所以用copy最安全。

3。到底用哪个?貌似还是用copy,因为copy并不一定导致一个新对对象创建,而牺牲效率。copy会调用NSCopying中的 -(id)copyWithZone:(NSZone *),我们可以判断下self是NSString还是NSMutableString,如果是NSString,就地[self  retain],[return self]。否则老老实实拷贝对象赋值,这样可以实现效率和安全的结合,实验的结果也是如此。

from:http://bukkake.iteye.com/blog/954259

这篇关于NSString 的copy和retain的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/333706

相关文章

Java 入门指南:Java 并发编程 —— Copy-On-Write 写时复制技术

文章目录 Copy-On-Write使用场景特点缺点CopyOnWrite 和 读写锁相同点之处不同之处 CopyOnWriteArrayList适用场景主要特性方法构造方法CopyOnWriteArrayList 使用示例 CopyOnWriteArraySet适用场景主要特性方法构造方法使用注意事项CopyOnWriteArraySet 使用示例 Copy-On-Writ

class _ContiguousArrayStorage deallocated with non-zero retain count

Xcode报错 : Object 0x11c614000 of class _ContiguousArrayStorage deallocated with non-zero retain count 2. This object's deinit, or something called from it, may have created a strong reference to self w

NSString处理

NSString *first = @"abdcbabcdbabcbacbcb";NSString *second = @"cdcdcdcd";NSString *third = @"string1:string2:string3:string4";NSArray *strings = [NSArray arrayWithObjects:first, second, third, nil];//

如何使用NSString结构体

// 处理这个纪录                  A_Record record_one;                  record_one  = [self get_one_from_html: str_one_record ]; 函数: -(A_Record )get_one_from_html:(NSString *)one_record

NSString 从文件里面读取字符串

-(NSString *) readFromFile:(NSString *)filePath {     NSString* content =@"";     //首先判断文件是否存在     if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])     {         content = [NSS

NSString to string [互相转换:支持中文]

NSString to string  const char* destDir = [filepath UTF8String]; string a=destDir; string to NSString NSString *s = [NSString stringWithUTF8String:str.c_str()];

2024.9.1 Python,跳跃游戏,贪心算法,回溯算法复原 IP 地址,关于回溯过程中列表的[:]以及copy问题再讨论

先祝各位C友们9月快乐,生活幸福。 1.跳跃游戏,贪心算法 昨天的三个代码我写到最后没时间去盘了,今天来盘一下,昨天我写的第一个代码从逻辑上就有问题,所以不停的报错不停的报错,我在报错的过程中不断地去加可能性,但是加一种可能就只解决一种问题,所以说明问题没有在根本上解决,所以我便在今天去看之前的代码有什么问题,我的代码如下: #错的class Solution:def jump(self,

NumPy(十三):数组的复制【.copy()】

import numpy as np# 数组的复制ar1 = np.arange(10)ar2 = ar1print('ar1 = {0}, ar2 = {1}'.format(ar1, ar2))print('ar2 is ar1: ', ar2 is ar1)# 回忆python的赋值逻辑:指向内存中生成的一个值 → 这里ar1和ar2指向同一个值,所以ar1改变,ar2一起改变ar1

NSData转NSString的问题

NSDataz转NSString的问题 NSData *wangguanDomindata = [NSDatadataWithData:(NSData *)[paraValueArrayobjectAtIndex:i]]; NSLog(@"wangguanDomindata--->%@-->%lu",wangguanDomindata,(unsignedlong)wangguanDomi

docker实战扩展四( Dockerfile 中,COPY . .详细讲解)

在 Dockerfile 中,COPY . . 是一个常用的指令,它的作用是将构建上下文中的所有文件复制到镜像中的指定目录。为了更好地理解这个指令,我们需要先了解两个概念:构建上下文和容器中的工作目录。 概念解释 构建上下文: 构建上下文是指在执行 docker build 命令时,Docker CLI 将指定目录的内容(包括子目录和文件)发送给 Docker 守护进程。构建上下文的路径通常