在类中初始化 NSString* 指针的方式

发布于 2024-10-30 19:37:40 字数 808 浏览 4 评论 0原文

我在我的类中使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

与往事干杯 2024-11-06 19:37:40
[NSString alloc] initWithString:@""]

归还您拥有的字符串,您必须释放它。

[NSString stringWithString:@""]

返回一个自动释放对象,该对象将由自动释放池释放并清理。

我建议您阅读 内存管理文档

[NSString alloc] initWithString:@""]

Gives back a string you own, you will have to release it.

[NSString stringWithString:@""]

Returns an autorelease object that will release and cleaned up by the autoreleasepool.

I would suggest you read the memory management documentation.

最佳男配角 2024-11-06 19:37:40

不同之处在于,在本例中 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文