简体   繁体   English

该代码是否泄漏内存(Objective-C全局变量)?

[英]Does this code leak memory (Objective-C global variables)?

Will these two functions leak memory if they get called many times? 如果这两个函数被多次调用,它们会泄漏内存吗? My knowledge of Objective-C is very rudimentary. 我对Objective-C的了解非常初级。 They seem fine to me but I don't have a good feeling about that implementation? 在我看来,它们看起来不错,但我对该实现没有很好的感觉? Should I remove that "retain"? 我应该删除“保留”吗? Is that a proper way to store objects globally? 这是全局存储对象的正确方法吗?

NSString* g_code = nil;

NSString* GetCode()
{
  if (!g_code)
  {
     std::string code = HelperFuncs::getCode();
     g_code = [[NSString stringWithUTF8String:code.c_str()] retain]; 
  }
  return g_code;
}

NSDictionary* g_options = nil;

- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary*)userInfo
{
    g_options = [[NSDictionary alloc] initWithDictionary:userInfo];
}

我将在这里应用单例模式 ,如果可能的话:使用ARC,这会使生活变得更加轻松。

If you don't know much about Objective-C and working on a Non ARC Project, then its really hard to handle memory. 如果您不太了解Objective-C和从事Non ARC项目,那么处理内存真的很困难。 One thing may help you, if you convert your project to ARC. 如果将项目转换为ARC,可能会有所帮助。 Go to Xcode -> Edit -> Convert -> To Objective-C ARC... This way convert your project to ARC and let me know if this helps 转到Xcode->编辑->转换-​​>到Objective-C ARC ...以这种方式将项目转换为ARC,让我知道是否有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM