• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag
 

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Fast Enumeration and remove elements
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Fast Enumeration and remove elements


  • Subject: Re: Fast Enumeration and remove elements
  • From: Quincey Morris <email@hidden>
  • Date: Sun, 18 Jan 2015 22:18:29 +0000

On Jan 18, 2015, at 12:45 , Trygve Inda <email@hidden> wrote:
>
> NSMutableDictionary* collection;  // keys are myID, values are MyObject
>
> for (MyObject* object in [[self collection] allValues])
> {
>    [collection removeObjectForKey:[object myID]];
> }

What Ken said, plus …

— If the collection of values is (as a matter of implementation) mutable, then I certainly wouldn’t want to rely on it not changing during the enumeration. If it is (as a matter of implementation) immutable, then it’s cost-free to copy. So the correct strategy is to copy it.

— It makes me uncomfortable to see you iterating through values, not keys. There is no API contract regarding uniqueness of the value objects, in the case that different keys refer to the same value object. Furthermore, your loop is logically incorrect in that case.

I know that might not matter here. Apparently, in the code fragment you showed, 1 unique key == 1 unique object. But even if that’s so it seems more correct to iterate over “allKeys” instead of “allObjects”.

Also, every time I do something like this, I wonder if it’s semantically preferable to use a block enumeration, which for a dictionary would have to be ‘keysOfEntriesPassingTest:’, followed by ‘removeObjectsForKeys:’. [I’m assuming your actual intent is to remove only some of the objects, because otherwise you’d use ‘removeAllObjects’ instead of a loop.]

I believe we found out, when the block enumeration API was introduced, that these don’t currently do anything particularly optimized, it seems to me that we can always hope that there will be such an optimization one day, so that the keysOf/remove pattern could be much more efficient for large dictionaries.

_______________________________________________

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


References: 
 >Fast Enumeration and remove elements (From: Trygve Inda <email@hidden>)

  • Prev by Date: Re: Fast Enumeration and remove elements
  • Next by Date: CVPixelBuffer and Color profiles
  • Previous by thread: Re: Fast Enumeration and remove elements
  • Next by thread: CVPixelBuffer and Color profiles
  • Index(es):
    • Date
    • Thread