Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Hour 15. Organizing Data with Collections > Testing Membership in a Collection

Testing Membership in a Collection

Each collection class has its own way of testing for membership. You can add code after the last step in the previous Try It Yourself to test for membership. Listing 15.3 shows how you can add your objects to a set. You can then test to see if one of the objects is in that set using the member method. It will return the object or nil if the object is not in the collection.

– (id)member:(id)object

The code snippet is shown in Listing 15.3.

Listing 15.3. Test for Membership in a Set


NSSet *mySet = [NSSet setWithObjects: myString, myNumber, myDate, nil];
NSLog (@"mySet:%@\n", [mySet description]);

anObject = [mySet member:myDate];
NSLog(@"member:%@\n",[anObject description]);


Experiment with adding other objects (and not adding objects) to watch the results. You can also simply ask if an object is a member of a collection (the result is YES or NO rather than the object itself).


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial