Re: [OT] [RANT]NSEnumerator
Re: [OT] [RANT]NSEnumerator
- Subject: Re: [OT] [RANT]NSEnumerator
- From: Greg Titus <email@hidden>
- Date: Thu, 31 Jan 2002 21:23:12 -0800
On Thursday, January 31, 2002, at 09:04 PM, Isaac Sherman wrote:
This is odd. I've been having a problem with NSEnumerators. They
always
seem to return nil, when I go to use them in a while loop, and the loop
never starts.
You should post your code for using them in a while loop so we can
figure out what the problem is there.
So, I wrote up a quick test, and it seems that you have to
send an NSEnumerator ivar (at least one created from an NSMutable
Dictionary) 2 nextObject messages instead of one (at least with custom
classes.
No, the quick answer here is: there is no guarantee when enumerating
over a dictionary that you'll get the objects back out in the same order
that you put them in. Your test app is expecting the enumerator to have
this behavior - it doesn't. The dictionary is returning the values for
stringThing3 first, then for stringThing1. If you called it a third
time, you'd get stringThing2's.
Then I realize this is just test code, but you have a bunch of
retain/release problems:
NSMutableDictionary * testDict=[[[NSMutableDictionary
alloc]init]retain];
StringThing * stringThing1=[[[StringThing alloc]initWithStrings:@"Foo"
string2:@"bar"]retain];
StringThing * stringThing2=[[[StringThing alloc]initWithStrings:@"Snafu"
string2:@"Dyah!"]retain];
StringThing * stringThing3=[[[StringThing alloc]init]retain];
Allocating something already retains it. These retain calls are
unneccesary and will result in memory leaks.
NSEnumerator * e=[[NSEnumerator alloc]init];
This enumerator never gets used. You replace it with the "e=[testDict
objectEnumerator];" line later on. Just discard the alloc, init here.
[e release];
You didn't allocate the enumerator that e represents. You got it from
[testDict objectEnumerator]. Since you didn't alloc, copy, or retain it,
you shouldn't release it.
[stringThing3release];
The other releases are fine, but you assigned stringThing3 to the result
of [e nextObject] - it doesn't neccesarilly point to the object it used
to, so this release is wrong.
Hope this helps,
--Greg