Correct way to set NSString inside NSMutableArray inside method

Consider the following codes

- (void) method1
{

list = [[NSMutableArray alloc] init];

NSString *f =[[NSString alloc] initWithCString: "f"];

 [list addObject: f];
}

- (void) method2...

list is a class instance variable, I need to access the whole variable inside the list in another method, for example method2 , when I allocate NSString in method1 , should I save it? I found that there is no need to save? Why?

+3
source share
3 answers

When you allochave something, you are already the owner, so there is no need for retainit.

Look here for the full story.

Your method (and class) is actually poorly written with regards to memory management. You should:

  • list,

  • list dealloc

, :

- (void) method1 {  
  [list release];
  list = [[NSMutableArray alloc] init];
  NSString *f = [[NSString alloc] initWithCString: "f"];
  [list addObject: f];
  [f release];
}

- (void) dealloc {
  [list release];
  // release other instance variables...
  [super dealloc];
}
+4
0

, , alloc . NSMutableArray. NSMutableArray retain .

, initWithCString . , C:

[NSString stringWithCString:"f" encoding:NSUTF8StringEncoding];

But if you just create a constant NSString, just use a literal. It is automatically automatically released and makes your intention more clear. i.e:.

list = [[NSMutableArray alloc] init]
[list addObject:@"f"];
0
source

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


All Articles