IPhone memory management

I am working on an application, and I would like to make sure that I manage the memory correctly and release everything that I have to. In my viewDidLoad method, I highlight some variables when determining which background is applied to the view (for internationalization), and the application works fine if I don't release it.

The problem is that if I release the variables, the application will crash. The code from viewDidLoad is shown below:

// Set the background image based on the phone 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];

Why would reset the backgroundImageName and language variables that caused the application to crash?

+3
source share
3 answers
NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];

language , objectAtIndex: . , , alloc ed, new ed copy ed, .

self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:backgroundImageName]];

UIColor ( alloc ).

NSString *backgroundImageName = [[NSString alloc] init];
backgroundImageName = [NSString stringWithFormat:@"background-%@.png",language];

, [[NSString alloc] init], ( alloc ed it). backgroundImageName, , , ( ). backgroundImageName , .

, UIColor . :

NSString *backgroundImageName = [NSString stringWithFormat:@"background-%@.png",language];

... ...

UIColor* backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:backgroundImageName]];
self.view.backgroundColor = backgroundColor;
[backgroundColor release];
+6

: , , init, .

. this

- , c

0

; . , "", "" "" ( ), . , , , , . : , .

Another problem in this code is that backgroundImageName is assigned twice. The first initialization is lost. Get rid of this, and just save the second one, and get rid of both calls -release, they are not needed.

0
source

Source: https://habr.com/ru/post/1728746/


All Articles