Re: newbie question on 'Cocoa Programming for Mac OS X'
Re: newbie question on 'Cocoa Programming for Mac OS X'
- Subject: Re: newbie question on 'Cocoa Programming for Mac OS X'
- From: "Jon B. Williams" <email@hidden>
- Date: Thu, 7 Feb 2002 16:55:46 -0800 (PST)
>
I'm just working my way through 'Cocoa Programming for Mac OS X' and
>
would like some feedback on something.
>
>
At the end of chapter 5 there are two challenges - the second one is to
>
delete multiple items out of a NSMutableArray, the issue being that as
>
you Enumerate through them the indexes shift.
Ah yes, I think I recall this exercise. One gets from a table view a list
of indices (sorted from smallest to largest) of the objects to be removed
from a mutable array. The list is in the form of an enumerator, and one
is tempted to use the enumerator as-is to go through the mutable array and
delete items at the specified indices. The trouble is that, as soon as
one item is deleted, the index of every subsequent item is shifted down by
one to fill in the gap, so the remaining items in the enumerator don't
match the indices of the objects you want to delete.
I solved the problem by reversing the order of the items in the
enumerator, so that you have a list of indices running from largest to
smallest, instead of smallest to largest. The re-indexing that
occurs upon deletion of an object from a mutable array only affects items
with higher indices than the one deleted, so you don't care about that if
you're deleting objects in reverse order of index. There's a very concise
way to reverse the order of the items in the enumerator:
NSEnumerator *e=[tableView selectedRowEnumerator];
e = [[e allObjects] reverseObjectEnumerator];
(I think this does it, I'm not at my mac so I can't check it at the
moment.)
[e allObjects] returns an array containing all the objects remaining in
the array, and
[someArray reverseObjectEnumerator] returns an enumerator of the objects
in the array, in reverse order.
This seems appealing to me because it avoids making creating the extra
array (tempArray in your code) full of objects to be deleted.
-JW
*************************************
Jon B. Williams
California Institute of Technology
Mail Code 12-33
1200 E. California Blvd.
Pasadena, CA 91125
Tel: (626)395-2619
Fax: (626)793-9506
**************************************
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.