Object-C, NSSet, unchangeable set
At night, continue the code.
At this time, dad made a phone call, "the sky is high, the sky is high, the birds fly", Dad is not bothering me for the old problem.
When I got free, I suddenly felt a lot of pressure.
How can this problem be solved ~
The first example is an immutable set.
Set is a general concept. It is nothing more than the Java. util. Set syntax in java, and the number of methods is inconsistent.
The core feature of the set is that the elements are not repeated and whether the elements are repeated depends on the hashCode and equals methods of the elements.
Code
/// Main. m // NSSetTest /// Created by fansunion on 15/12/3. // Copyright (c) 2015 demo. All rights reserved. // # import
// Define a function that converts an Array or NSSet set to a string NSString * NSCollectionToString (id collection) {NSMutableString * str = [NSMutableString stringWithString: @ "["]; // use the for-each loop syntax to traverse the for (id obj in collection) {[str appendString: [obj description]; [str appendString: @ ","];} // get the string length, remove the last two extra characters NSUInteger length = [str length]; [str deleteCharactersInRange: NSMakeRange (length-2, 2)]; [str appendString: @ "]"]; return Str;} // NSSet is an unchangeable set, and the variable set is NSMutableSet. // A bird-like int main (int argc, const char * argv []) with NSArray and NSMutableArray {@ autoreleasepool {// constructs a set of four elements, two of them are repeated NSSet * set1 = [NSSet setWithObjects: @ "A", @ "B", @ "C", @ "B", nil]; NSLog (@ "The set1 count: % ld", [set1 count]); NSLog (@ "The set1: % @", NSCollectionToString (set1 )); // set1 is an unchangeable set NSSet * set2 = [set1 setByAddingObject: @ "D"]; NSLog (@ "The new set1: % @", NSCollectionToString (set1 )); NSLog (@ "The set2: % @", NSCollectionToString (set1); BOOL isSubSet = [set1 isSubsetOfSet: set2]; NSLog (@ "The set1 is subSet of set2: % d ", isSubSet); BOOL have = [set1 containsObject: @" C "]; NSLog (@" The set1 has C: % d ", have );} return 0 ;}
Running result
20:16:52. 049 NSSetTest [5903: 419290] The set1 count: 3
20:16:52. 050 NSSetTest [5903: 419290] The set1: [A, B, C]
20:16:52. 050 NSSetTest [5903: 419290] The new set1: [A, B, C]
20:16:52. 051 NSSetTest [5903: 419290] The set2: [A, B, C]
20:16:52. 051 NSSetTest [5903: 419290] The set1 is subSet of set2: 1
20:16:52. 051 NSSetTest [5903: 419290] The set1 has C: 1
Program ended with exit code: 0
According to the current learning progress, there is no problem in understanding Object-C and iOS before March 31, 2017.