Re: Allocate memory for object
Re: Allocate memory for object
- Subject: Re: Allocate memory for object
- From: Jonathon Mah <email@hidden>
- Date: Sun, 12 Dec 2004 00:47:23 +1030
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@hidden
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden