Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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.