Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Build a Playlist Browser with Objective-C Refactoring Our Code Passing Playlist Objects Using Segues

Ruggiero A
Ruggiero A
8,534 Points

Wouldn't it be better check index for (!)NSNotFound instead of scanning twice the NSArray?

In this piece of code:

if([_playlistImageViews containsObject:playlistImageView]) {
    NSUInteger index = [_playlistImageViews indexOfObject:playlistImageView];

    PlaylistDetailViewController *playlistDetailController = (PlaylistDetailViewController *)segue.destinationViewController;

    playlistDetailController.playlist = [[Playlist alloc] initWithIndex:index];
}

The array _playlistImageViews is queried twice, first with function containsObject, second with indexOfObject (which actually are pretty similar), so the array will be scanned twice. I watched Docs of method indexOfObject and saw that it actually returns NSNotFound integer value when the object is not in the array, so you can actually ask only once where the object is, and if there is no object, you get NSNotFound value as reutrn.

So

NSUInteger index = [_playlistImageViews indexOfObject:playlistImageView];
if(index != NSNotFound) {
      PlaylistDetailViewController *playlistDetailController = (PlaylistDetailViewController *)segue.destinationViewController;

      playlistDetailController.playlist = [[Playlist alloc] initWithIndex:index];
}

The Array is scanned only once, but doing actually the same.