13.07.2015 Views

Beginning Objective-C pdf - EBook Free Download

Beginning Objective-C pdf - EBook Free Download

Beginning Objective-C pdf - EBook Free Download

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

58CHAPTER 3: Foundational APIsTesting for inclusion of an object in a set looks similar to testing for inclusion in an array.There are two methods: one returns a BOOL indicating whether or not an object is in a set, andthe other returns the object itself. It is a fine distinction, but important. The two methods arecontainsObject: and member:.Listing 3-27. Testing for Inclusion in SetsNSSet *set = [NSSet setWithObjects:@"apples", @"milk", @"bananas"];NSString *string = @"apples";if ([set containsObject:string])NSLog(@"This is printed because the set contains an object that matches the parameterstring");NSString *stringContainedInSet = [set member:string];After the code in Listing 2-27 has finished executing, stringContainedInSet points to the actualinstance contained in the set.If you need any object contained within a set, use the anyObject method; it will return an objectwithin the receiver.Since you cannot access specific objects in a set based on their index (they have no index),enumerating over a set directly using a for loop is impossible. Instead, call allObjects on anNSSet instance to generate an NSArray containing the same objects that are in the set. The orderof the objects in the array is undefined; do not rely on a specific order.Listing 3-28. Testing for Inclusion in SetsNSSet *set = [NSSet setWithObjects:@"apples", @"milk", @"bananas"];NSArray *array = [set allObjects];for (NSString *string in array){NSLog(@"%@", string);}The code in Listing 3-28 prints out the words “apple”, “milk”, and “bananas” in some order tothe console log.It’s possible to test for more than just inclusion of a particular object in a set. The methodsintersectsSet:, isEqualToSet:, and isSubsetOfSet: allow you to test if a receiving setintersects with, is equal to, or is a subset of another set, respectively.Mutable SetsMutable sets are to set as mutable arrays are to arrays. The mutable set object in the Foundationframework is NSMutableSet and it extends NSSet. The two most simple methods provided byNSMutableSet are addObject: and removeObject:. By now, you should expect that any attemptto remove an object that does not exist in a mutable set generates a runtime exception (luckily,testing for inclusion in a set is a performed in constant-time, so you have no excuse not tocheck first!).If you want to add more than one object to a set at a time, use the addObjectsFromArray:method.www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!