Skip navigation.
 
mlRe: Allocate memory for object
FROM : Jonathon Mah
DATE : Sat Dec 11 15:17:23 2004

On 11 Dec 2004, at 20:23, Apirak wrote:

> I try to add two object to myArray by one variable. my source code is
> look like this
>
>     NSMutableArray *myArray = [[NSMutableArray alloc] init];
>     
>     Word *word;
>         
>     word = [[Word alloc] init];
>     [word setWord:@"test"];
>     [myArray addObject:word];
>     
>     word = nil;
>     word = [[Word alloc] init];
>     [word setWord:@"test2"];
>     [myArray addObject:word];
>     
>     Word *wd = [[myArray objectAtIndex:0] retain];
>     NSLog(@"word equal %@", [wd getWord]);
>     
>     wd = [[myArray objectAtIndex:1] retain];
>     NSLog(@"word equal %@", [wd getWord]);
>
> the result is
>
> word equal test2
> word equal test2
>
> but It should be
>
> word equal test
> word equal test2
>
> I am java developer, it very hard to deal with vector :(


You are right; it should be that. Can you send me the rest of the code?

Also, in the code you provided in your e-mail, you have some memory
management issues. Just briefly:
You are alloc-initting a Word, then putting it in an array. Since you
want to give the array ownership of the word, you should release it
after adding it. The basic rule is: If you alloc, copy, or retain, you
must release.

Word *word;

word = [[Word alloc] init];
[word setWord:@"test"];
[myArray addObject:word];
[word release];

word = [[Word alloc] init];
[word setWord:@"test2"];
[myArray addObject:word];
[word release];

Secondly, there is no need to retain the words when you get the out of
the array. If you want to retain them (for example, if there was a
possibility that the array would disappear during that piece of code),
you must release them later.


Anyway, send me the code and I'll take a look.



Jonathon Mah
<email_removed>

Related mailsAuthorDate
mlAllocate memory for object Apirak Dec 11, 10:53
mlRe: Allocate memory for object Jonathon Mah Dec 11, 15:17
mlRe: Allocate memory for object Jonathan Jackel Dec 11, 18:34
mlRe: Allocate memory for object Andrew Merenbach Dec 12, 10:32