正在分配 self.string = @""在一个(保留)正确的@property上?

发布于 2024-12-01 05:20:02 字数 218 浏览 1 评论 0 原文

一个哲学问题。将常量字符串分配给(保留的)@property是否正确?或者,我应该这样做 self.string = [NSString stringWithString:@""];

是否存在内存泄漏?如果释放过多怎么办?

它是一个常量字符串,那么它的行为方式与 NSString 对象相同吗?

如果属性是(分配),是否意味着它在运行循环后将无效?

A philosophical question, of sorts. Is it proper to assign a constant string to an @property that's (retained)? Or, should I do self.string = [NSString stringWithString:@""];

Is there a memory leak? What if it's overreleased?

It's a constant string, so does it behave the same way as an NSString object?

If the property is (assign) does that mean it will not be valid after the run loop?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

墟烟 2024-12-08 05:20:02

是的,没关系。无论您采用哪种方式,常量字符串仍然会被编译到您的程序中(因为无论如何您都必须在 [NSString stringWithString:@""] 中使用它)。常量字符串实际上不会被保留/释放,但重要的是它的语义:你正在分配一个字符串(就你而言,它有一个 net +0 keepCount - 你没有 分配它,所以你不拥有它)到一个将拥有它所有权的财产。如果该属性是(assign),那么它仍然可以使用常量字符串,但在自动释放池耗尽后它将在语义上无效。

Yes, it's fine. No matter which way you do it, the constant string will still be compiled into your program (because you have to use it in [NSString stringWithString:@""] anyway). Constant strings don't actually get retained/released, but the what matters is the semantics of it: you're assigning a string (which has a net +0 retainCount as far as you're concerned — you haven't alloced it, so you don't own it) to a property which will take ownership of it. If the property is (assign), then it may still work with a constant string, but it will be semantically invalid after the autorelease pool drains.

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