iPhone内存管理 [英] iPhone Memory Management
问题描述
我正在开发一个应用程序,我想确保我正确地管理内存并释放我应该做的一切。在我的viewDidLoad方法中,我分配一些变量来确定要应用于视图的背景(用于国际化),如果我不释放它们,应用程序就可以正常工作。
I'm working on an app and I'd like to make sure that I'm managing memory properly and releasing everything that I should. In my viewDidLoad method I allocate some variables in determining which background to apply to the view (for internationalization) and the app works fine if I don't release them.
问题是,如果我发布变量,应用程序将崩溃。 viewDidLoad中的代码如下:
The problem is that if I release the variables the app will crash. Code from viewDidLoad is below:
// Set the background image based on the phone's preferred language
NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];
NSString *backgroundImageName = [[NSString alloc] init];
backgroundImageName = [NSString stringWithFormat:@"background-%@.png",language];
self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:backgroundImageName]];
... do some more initialization stuff ...
// IF THE FOLLOWING ARE RELEASED THE APP WILL CRASH!!!
//[backgroundImageName release];
//[language release];
为什么发布backgroundImageName和语言变量导致应用程序崩溃?
Why would releasing the backgroundImageName and language variables cause the app to crash?
推荐答案
NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];
此处,语言
不需要是因为 objectAtIndex:
为你自动释放它而发布。按照惯例,如果您 alloc
ed, new
ed或,则拥有一个对象复制
编辑它,否则你没有。
Here, language
does not need to be released because objectAtIndex:
autoreleases it for you. By convention, you own an object if you've alloc
ed, new
ed, or copy
ed it, otherwise you don't.
self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:backgroundImageName]];
这里, UIColor
对象确实需要被释放(因为你 alloc
ed it)。
Here, the UIColor
object does need to be released (because you alloc
ed it).
NSString *backgroundImageName = [[NSString alloc] init];
backgroundImageName = [NSString stringWithFormat:@"background-%@.png",language];
这里是 [[NSString alloc] init]返回的字符串
确实需要发布(因为你已经 alloc
ed it)。但是,下一行更改 backgroundImageName
以指向新的自动释放字符串,丢失对原始字符串的最后一次引用而不释放它(内存泄漏)。 backgroundImageName
不应该被释放,因为它已经被自动释放。
Here the string returned by [[NSString alloc] init]
does need to be released (because you've alloc
ed it). However, the next line changes backgroundImageName
to point to that a new autoreleased string, losing the last reference to the original string without releasing it (a memory leak). backgroundImageName
should not be released because it is already autoreleased.
你可以通过释放<$ c来避免泄漏$ c> UIColor 并消除未使用的字符串。例如:
You can avoid the leaks by releasing the UIColor
and eliminating the unused string. For example:
NSString *backgroundImageName = [NSString stringWithFormat:@"background-%@.png",language];
...和...
UIColor* backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:backgroundImageName]];
self.view.backgroundColor = backgroundColor;
[backgroundColor release];
这篇关于iPhone内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!