Re: remove elements during the iteration on NSMutableDictionary
Re: remove elements during the iteration on NSMutableDictionary
- Subject: Re: remove elements during the iteration on NSMutableDictionary
- From: Roland King <email@hidden>
- Date: Thu, 07 Aug 2008 00:30:44 +0800
for (id theKey in aDictionary) {
id anObject = [[aDictionary objectForKey:theKey] retain];
[aDictionary removeObjectForKey:theKey];
// Question: will this removal break or corrupt the loop of
enumerating the
elements?
[anObject someMessage];
[anObject release];
}
Oops, I diid not see that, sorry.
Yup, that works. I prefer:
[id anObject = [[aDictionary objectForKey:theKey] retain]
autorelease];
That allows breaks inside the loop. (And you do not forget the -
release, as you did.)
Amin
or send it a message before you remove it from the dictionary.
for( id theKey in aDictionary ){
id anObject = [[ aDictionary objectForKey:theKey ];
[ anObject someMessage ];
[ aDictionary removeObjectForKey:theKey ];
}
of course as the original response pointed out, you can't really do
this anyway as the modification will cause an exception so you don't
really have the problem, you can't really remove the object where
you're removing it.
One question I had, the mutable guard which raises the exception,
that's only there because of the use of fast-enumeration, am I right?
Had you used an NSEnumerator I believe it's still not safe to remove
objects, but I don't think you get the exception, you just need to
know you mustn't do it.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden