开发者

Correct way to put NSString inside NSMutableArray inside a method

Consider the following codes

- (void) method1
{

list = [[NSMutableArray alloc] init];

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

开发者_开发问答 [list addObject: f];
}

- (void) method2...

list is an instance variable of a class, I need to access all the variable inside the list in another method such as method2, when I alloc a NSString in method1, should I need to retain it? I found that that no retain is needed? Why?


When you alloc something, you're the owner already, so there's no need to retain it.

Look here for the full story.

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

  1. release the list before allocating and assigning a new list to it

  2. release the list in the dealloc method

  3. release the string after you add it to the array

So change your methods to:

- (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];
}


you will need to an @ for that string @"f"

and this covers the memory management issue NSMutableArray memory management


You don't need to retain it, as you are the owner when you alloc a class and receive an instance. You will actually need to release it after adding to NSMutableArray. When adding objects to NSMutableArray, it sends them a retain message and takes ownership.

Also, note that initWithCString is deprecated. Use the following pattern instead if you need to init from a C string:

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

But if you're just creating a constant NSString, just use the literal. It's automatically auto-released and makes your intent more clear. i.e.:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜