在类中初始化 NSString* 指针的方式
我在我的类中使用 NSString ,并且经常需要将字符串值复制到另一个类。但我的问题是我应该如何初始化字符串,例如 init
? (值是类成员,以下调用在 init 中)
value = [NSString stringWithCString:inStrning encoding:NSASCIIStringEncoding];
或者
value = [[NSString alloc] initWithCString:inStrning encoding:NSASCIIStringEncoding];
这里有什么区别? init 完成后,第一次调用中分配的内存是否会释放? 我使用 value
作为 assign
属性。使用copy
会更好吗?
当我使用某种方法将字符串传递给类时复制字符串怎么样?示例:
-(id) initWithObjectTypeStr:(NSString*)inTypeStr
{
...
objectTypeStr = [NSString stringWithString:inType];
//or
objectTypeStr = [[NSString alloc] initWithString:inType];
}
objectTypeStr
未定义为属性,因此它具有默认属性(我认为assign
)。
在这种情况下使用的最佳做法是什么?
I'm using NSString
in my classes and often need to copy string value to another class. But my question is how should I initialize string in, for example init
?
(value is class member and the following calls are in init)
value = [NSString stringWithCString:inStrning encoding:NSASCIIStringEncoding];
or
value = [[NSString alloc] initWithCString:inStrning encoding:NSASCIIStringEncoding];
What is the difference here? Does a memory allocated in 1st call released when init finishes?
I'm using value
as a assign
property. Would it be better to use copy
?
And what about copying string when I'm passing it to class using some method? Example:
-(id) initWithObjectTypeStr:(NSString*)inTypeStr
{
...
objectTypeStr = [NSString stringWithString:inType];
//or
objectTypeStr = [[NSString alloc] initWithString:inType];
}
objectTypeStr
is not defined as property so it has default properties (assign
I think).
What is the best practice to use in this case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
归还您拥有的字符串,您必须释放它。
返回一个自动释放对象,该对象将由自动释放池释放并清理。
我建议您阅读 内存管理文档。
Gives back a string you own, you will have to release it.
Returns an autorelease object that will release and cleaned up by the autoreleasepool.
I would suggest you read the memory management documentation.
不同之处在于,在本例中
objectTypeStr = [NSString stringWithString:inType];
objectTypeStr
是自动释放的,并且您不拥有该对象。而在
objectTypeStr = [[NSString alloc] initWithString:inType];
您拥有该对象的所有权,因为您使用 alloc 或 new 分配它,因此您有责任在使用后释放它
The difference is that in this case
objectTypeStr = [NSString stringWithString:inType];
objectTypeStr
is auto-released and you dont own the object.Whereas in
objectTypeStr = [[NSString alloc] initWithString:inType];
you take ownership of the object since you are allocating it using alloc or new so its your responsibility to release it after its use