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: Jonathan deWerd <email@hidden>
- Date: Wed, 6 Aug 2008 11:13:59 -0600
On Aug 6, 2008, at 10:49 AM, Andrew Merenbach wrote:
On Aug 6, 2008, at 9:30 AM, Roland King wrote:
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._______________________________________________
May I suggest the following?
-----
NSMutableArray *keysToRemove = [NSMutableArray array];
for (id theKey in aDictionary) {
[keysToRemove addObject:theKey];
}
[aDictionary removeObjectsForKeys:keysToRemove];
You can even use -[NSDictionary objectsForKeys:notFoundMarker:] to
send a single message to the dictionary's objects using -
makeObjectsPerformSelector:
Cheers,
Andrew
You could also use performSelector:withObject:afterDelay: assuming
that you'll reenter the run loop before you need the objects removed.
_______________________________________________
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:
@gmail.com
This email sent to email@hidden
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
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