NSMutableString 对象声明为 extern 的问题

发布于 2024-11-03 17:42:19 字数 321 浏览 0 评论 0原文

在我的应用程序中,我需要将 NSMutableString 从一个类传递到另一个类,因此我将其放在外部。问题是,当我运行应用程序时,该类仅访问该字符串一次,即应用程序第二次崩溃时!显然,第一次访问后 NSMutablString 就变成了 nil。所以我试图弄清楚一些事情:我将字符串转换为 C 字符。好吧,这次应用程序没有崩溃,但是......每次我调用它时,字符的值都会改变! 我真的很困惑:请问我需要知道

  1. 是否有任何方法可以维护 NSMutablString 的值,以便每次类调用它时它都可用?
  2. 是什么导致 char 的值发生变化?

感谢您的帮助

in my app i need to pass a NSMutableString from one class to another so i put it extern.The problem is that when i run the app, the class does only access the string once, the second time the app crashes !! Obviously the NSMutablString becames nil after the first access. So i tried to figure out something: i converted the string into a C char. Well this time the app doesn't crash, but.. the value of the char changes everytime i call it !!
Am really confused: Please i need to know

  1. Is there any way to maintain the value of the NSMutablString so it would be available everytime a class calls it ?
  2. What causes the changing in the char's value ?

Thanks for any help

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

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

发布评论

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

评论(1

岁月苍老的讽刺 2024-11-10 17:42:19

听起来你确实在做一些奇怪的事情。

  • 如果你想将 NSMutableString 实例从一个对象(源)传递到另一个对象(目标),你应该将其分配给目标对象的属性,或者通过某种方法调用传递它。

  • 目标对象应该保留此实例(显式地或使用属性的“保留”标志),以确保无论源对象做什么,该实例都是有效的。当不再需要时,目标对象也应该释放它,否则会引入内存泄漏。

  • “NSMutableString(指针)变为 nil”并不是很明显。任何无效的引用(不仅仅是 nil)都可能在取消引用时导致崩溃。实际上,我的猜测是您正在尝试访问已删除的对象。

  • 我猜你已经使用了 [NSMutableString cStringUsingEncoding:] 或类似的方法来获取 char 指针。请记住,返回的指针在有限时间内有效,请检查文档。

无论如何,这都是非常基本的东西。您应该阅读内存管理编程指南并确保你理解一切。开发稳定的 Objective-C 代码非常重要。

It sounds like you're doing some weird thing, really.

  • If you want to pass the NSMutableString instance from one object (source) to another (target), you should either assign it to the target object's property, or pass it via some method call.

  • The target object should retain this instance (either explicitly, or using 'retain' flag of the property), to ensure the instance is valid regardless of what the source object does. The target object should also release it, when it is no longer needed, otherwise you'd introduce a memory leak.

  • It is not really obvious, that "NSMutableString (pointer) becomes nil". Any invalid reference can lead to a crash when dereferenced, not only nil. Actually, my guess is that you're trying to access a deleted object.

  • I guess you've used [NSMutableString cStringUsingEncoding:] or similar method to get char pointer. Keep in mind that the pointer returned is valid for a limited time, check the docs.

Anyway, this is all pretty basic stuff. You should read Memory Management Progamming Guide and make sure you understand everything. It's simply essential to develop a stable Objective-C code.

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