Objective-C:关于 NSString 和范围的问题
我有一个全局 NSString 变量,它在我的 ViewController.m 文件中声明,在任何方法之外,但不在我的 .h 文件中。
NSString *menuString;
它在 webViewDidFinishLoad
内部初始化,当我这样做时它可以工作
NSString *menu = [self getParameter:url :@"Menu"];
menuString = [menu copy];
,但当我这样做时它不起作用
NSString *menu = [self getParameter:url :@"Menu"];
menuString = menu;
,或者
menuString = [self getParameter:url :@"Menu"];
这里,“它有效”是指该值被保存,我可以在其他方法中使用它。否则,在调试期间,它会说 menuString 超出范围。我想知道为什么它的行为会根据初始化而有所不同。
(getParameter 只是一个接受两个字符串并返回一个字符串的方法)。
谢谢!
I have a global NSString variable that I declared in my ViewController.m file, outside of any methods, but not in my .h file.
NSString *menuString;
It is initialized inside webViewDidFinishLoad
and it works when I do this
NSString *menu = [self getParameter:url :@"Menu"];
menuString = [menu copy];
but not when I do this
NSString *menu = [self getParameter:url :@"Menu"];
menuString = menu;
or
menuString = [self getParameter:url :@"Menu"];
Here, by "it works" I mean the value is saved and I can use it in other methods. Otherwise, during debug, it says that menuString is out of scope. I was wondering why it behaves differently depending on the initialization.
(getParameter is just a method that takes two strings and returns a string).
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
方法
getParameter:
返回一个自动释放的NSString
对象。这意味着该对象将在该运行循环结束时自动释放(当自动释放池耗尽时)。
因为您从未保留过该对象,所以一旦它被自动释放,它就会被释放,您将无法再使用它。
通过执行
复制
,您将创建该对象的保留副本,该副本不会在运行循环结束时自动释放。如果您使用
retain
,它也会起作用:请注意,如果您
复制
或retain
它,则必须在稍后的某个时刻释放它。不再需要它,否则会出现内存泄漏。The method
getParameter:
returns an autoreleasedNSString
object.That means that this object will be automatically released at the end of that run loop (when the autorelease pool is drained).
Because you never retained that object, once it's autoreleased it's dealloced and you can't use it anymore.
By doing a
copy
, you are creating a retained copy of that object that won't be autoreleased at the end of the run loop.It would also work if you used
retain
:note that if you
copy
orretain
it, you have to release it later at some point when you don't need it anymore, otherwise you'll have a memory leak.[self getParameter:url :@"Menu"];
返回一个autoreleased
字符串对象。这意味着在自动释放池的下一个周期中它将被释放。如果没有其他因素增加其保留计数(retain
或copy
调用),它将被释放。一旦它被释放并且你尝试使用它你就会崩溃。在第一个示例中,您复制了字符串,现在您拥有一个对象,当自动释放池清理时,该对象不会被清理。
但是,请确保在类的
dealloc
方法中release
该对象,以防止泄漏。[self getParameter:url :@"Menu"];
returns anautoreleased
string object. This means during the next cycle of the Autorelease Pool it will be released. If nothing else has increased its retain count (retain
orcopy
call), it will be dealloc'd. Once it's dealloc'd and you attempt to use it you will crash.Your first example, you copy the string you now have an object that will not be cleaned up when the Autorelease Pool cleans up.
However, make sure you
release
the object in your class'sdealloc
method to prevent an leaks.