2010-05-25 107 views
1

我的应用程序充斥着关于NSString对象的内存泄漏。永远不要使用alloc创建一个NSString对象,但根据Instruments(与真实设备一起使用),应用程序会泄漏NSString对象。 这发生在stringByAppendingString的使用周围。代码示例:NSString创建没有alloc,内存泄漏

NSString *documentsPathPlusSlash = [self.documentsPath stringByAppendingString:@"/"]; 
NSString *documentsPathPlusSlashAndFileName = [documentsPathPlusSlash stringByAppendingString:fileName]; 
mainMenuViewController.documentsPath = documentsPathPlusSlashAndFileName; 

一旦这是一个长的语句,所以我想也许拆分为单独的行会解决这个问题。没有这样的运气,上面的代码泄漏NSString对象。这是为什么? MainMenuViewController.dealloc不会发布documentsPath,因为这不是必需的。或者是?苹果文档和各种论坛并没有真正的帮助。

回答

2

这是为什么? MainMenuViewController.dealloc不会发布documentsPath,因为这不是必需的。或者是?

这取决于documentsPath属性是如何在您的mainMenuViewController中定义的。如果它被定义为retaincopy属性(很可能是这样),那么你的控制器通过递增字符串对象来“占有”它保留计数,并且它有责任在dealloc方法中释放它 - 所以你需要在这种情况下发布。

+0

谢谢!解决了。 NSString是特殊对象。 – 2010-05-25 14:14:02

+0

那么究竟是什么问题呢? – Vladimir 2010-05-25 14:29:33

0

取决于如何声明和实施文件路径。在最简单的情况下,当documentsPath是@property(保留)与@synthesized二传手,你还需要将其设置为nil在你的dealloc:

mainMenuViewController.documentsPath = nil 
+0

谢谢!解决了。虽然我更喜欢[documentsPath版本]。实际上,我在互联网上发现了一个页面,显示了5种不同的实现dealloc的方式。 [x发布]是Apple在其示例代码中使用的。 – 2010-05-25 14:15:27