在这种情况下,NSMutableString比NSString更有效吗? [英] Is an NSMutableString in this case more efficient than NSString?
问题描述
如果我以这种方式声明一个指针变量:
If I declare a pointer variable in this fashion:
NSString *foo;
然后在我的代码中的某处做一些事情,例如:
And then somewhere later in my code do something such as:
foo = @"bar";
这是最终采用我的NSString,在内存中创建一个新的副本与一个额外的字符串,然后删除我的初始字符串?
Is that ultimately taking my NSString, creating a new copy in memory with an additional string, then deleting my initial string? Would foo be better off as an NSMutableString?
推荐答案
不, foo
是一个指向 NSString
的指针的变量。分配 foo = @bar
将指针 foo
存储的值设置为NSString的地址 @bar
。没有拷贝。如果 foo
已经指向另一个 NSString
实例不是一个字符串constsant像 @bar
),没有其他引用,那么你有一个内存泄漏。
No, foo
is variable holding a pointer to an NSString
. The assignment foo = @"bar"
sets the value stored by the pointer foo
to the address of the NSString @"bar"
. There is no copy made. If foo
already pointed to an other NSString
instance that was not a string constsant (i.e. like @"bar"
) and there are no other references to that instance, then you have a memory leak. You would
[foo release];
foo = @"bar";
您不需要保留或释放字符串常量,例如 @bar
。
in that case. You do not need to retain or release string constants like @"bar"
.
字符串常量不能改变,所以如果你尝试修改常量字符串的值,你会得到一个运行时错误。将 @bar
分配给 NSString *
与之间没有区别NSMutableString *
。当然,你不能使用 NSMutableString
的变异方法而没有运行时错误,只是因为你分配了@bar的地址(一个NSString实例)到 NSMutableString *
类型的变量。如果你想改变字符串,你会做
String constants cannot be mutated, so you will get a runtime error if you try to modify the value of a constant string. There's no difference between assigning @"bar"
to an NSString*
vs an NSMutableString*
. Of course, you won't be able to use the mutating methods of the NSMutableString
without a runtime error just because you assign the address of @"bar" (an NSString instance) to a variable of type NSMutableString*
. If you want to mutate the string, you would do
NSMutableString *mutableFoo = [@"bar" mutableCopy];
在这种情况下,显然会有一个副本,并且您负责发布 mutableFoo
当你完成它。
In this case, a copy is obviously made and you are responsible for releasing mutableFoo
when you're done with it.
这篇关于在这种情况下,NSMutableString比NSString更有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!