Summary of NSArray, NSSet, and NSDictionary in ios

Source: Internet
Author: User
Tags hash

Three collection classes are used to collect cocoa objects (NSObject objects ):
NSArray is used for object ordered sets (equivalent to arrays)
NSSet is used for unordered objects.
NSDictionary for key-value ing
The above three collection classes are unchangeable (once initialized, they cannot be changed)

The following are three types of variable collection classes (these three variable collection classes correspond to the subclasses of the above three collection classes ):
NSMutableArray
NSMutableSet
NSMutableDictionary

Note: these collection classes can only collect cocoa objects (NSOjbect objects). If you want to save some original C data (such as int, float, double, BOOL, etc ), you need to encapsulate the original C data into the NSNumber type. The NSNumber object is a cocoa object and can be saved in the collection class.

NSArray
Ordered collection of objects. Immutable. You cannot add or remove objects to it once it's created.
Important methods:
+ (Id) arrayWithObjects :( id) firstObject,...; // nil terminated
-(Int) count;
-(Id) objectAtIndex :( int) index; // NSString * s1 = [[myarray objectAtIndex: 0];
-(Void) makeObjectsPerformSelector :( SEL) aSelector;
-(NSArray *) sortedArrayUsingSelector :( SEL) aSelector;
-(Id) lastObject; // returns nil if there are no objects in the array (convenient)
Note:
Class method arrayWithObjects can create an autoreleased NSArray of the items. For example:
@ Implementation MyObject
-(NSArray *) coolCats {
Return [NSArray arrayWithObjects: @ "Steve", @ "Ankush", @ "Sean", nil];
}
@ End
Other convenient create with methods (all return autoreleased objects ):
[NSString stringWithFormat: @ "Meaning of % @ is % d", @ "life", 42];
[NSDictionary dictionaryWithObjectsAndKeys: ankush, @ "TA", janestudent, @ "Student", nil];
[NSArray arrayWithContentsOfFile :( NSString *) path];
----- Create an array -----
// NSArray * array = [[NSArray alloc] initWithObjects:
@ "One", @ "Two", @ "Three", @ "Four", nil];

Self. dataArray = array;
[Array release];

//-(Unsigned) Count; number of objects contained in the array;
NSLog (@ "self. dataArray cound: % d", [self. dataArray count]);

//-(Id) objectAtIndex: (unsigned int) index; get the object at the specified index;
NSLog (@ "self. dataArray cound 2: % @", [self. dataArray objectAtIndex: 2]);

------ Copying data from an array to another array (variable level )-------

// ArrayWithArray:
// NSArray * array1 = [[NSArray alloc] init];
NSMutableArray * MutableArray = [[NSMutableArray alloc] init];
NSArray * array = [NSArray arrayWithObjects:
@ "A", @ "B", @ "c", nil];
NSLog (@ "array: % @", array );
MutableArray = [NSMutableArray arrayWithArray: array];
NSLog (@ "MutableArray: % @", MutableArray );

Array1 = [NSArray arrayWithArray: array];
NSLog (@ "array1: % @", array1 );

// Copy

// Id obj;
NSMutableArray * newArray = [[NSMutableArray alloc] init];
NSArray * oldArray = [NSArray arrayWithObjects:
@ "A", @ "B", @ "c", @ "d", @ "e", @ "f", @ "g", @ "h ", nil];

NSLog (@ "oldArray: % @", oldArray );
For (int I = 0; I <[oldArray count]; I ++)
    {       
Obj = [[oldArray objectAtIndex: I] copy];
[NewArray addObject: obj];
    }
//
NSLog (@ "newArray: % @", newArray );
[NewArray release];

// Quick enumeration
// NSMutableArray * newArray = [[NSMutableArray alloc] init];
NSArray * oldArray = [NSArray arrayWithObjects:
@ "A", @ "B", @ "c", @ "d", @ "e", @ "f", @ "g", @ "h ", nil];
NSLog (@ "oldArray: % @", oldArray );

For (id obj in oldArray)
    {
[NewArray addObject: obj];
    }
//
NSLog (@ "newArray: % @", newArray );
[NewArray release];

// Deep copy

// NSMutableArray * newArray = [[NSMutableArray alloc] init];
NSArray * oldArray = [NSArray arrayWithObjects:
@ "A", @ "B", @ "c", @ "d", @ "e", @ "f", @ "g", @ "h ", nil];
NSLog (@ "oldArray: % @", oldArray );
NewArray = (NSMutableArray *) CFPropertyListCreateDeepCopy (kCFAllocatorDefault, (CFPropertyListRef) oldArray, kCFPropertyListMutableContainers );
NSLog (@ "newArray: % @", newArray );
[NewArray release];

// Copy and sort

// NSMutableArray * newArray = [[NSMutableArray alloc] init];
NSArray * oldArray = [NSArray arrayWithObjects:

NSMutableArray
Mutable version of NSArray.
-(Void) addObject :( id) anObject;
-(Void) insertObject :( id) anObject atIndex :( int) index;
-(Void) removeObjectAtIndex :( int) index;
-(Void) removeAllObjects;

----- Allocate capacity to the array -----
// NSArray * array;
Array = [NSMutableArray arrayWithCapacity: 20];

----- Add an object at the end of the array -----
//-(Void) addObject: (id) anObject;
// NSMutableArray * array = [NSMutableArray arrayWithObjects: @ "One", @ "Two", @ "Three", nil];
[Array addObject: @ "Four"];
NSLog (@ "array: % @", array );

----- Delete the object at the specified index in the array -----
//-(Void) removeObjectAtIndex: (unsigned) index;
// NSMutableArray * array = [NSMutableArray arrayWithObjects: @ "One", @ "Two", @ "Three", nil];
[Array removeObjectAtIndex: 1];
NSLog (@ "array: % @", array );

----- Array enumeration -----
// 1.-(NSEnumerator *) objectEnumerator; // forward and backward
// NSMutableArray * array = [NSMutableArray arrayWithObjects: @ "One", @ "Two", @ "Three", nil];
NSEnumerator * enumerator;
Enumerator = [array objectEnumerator];

Id thingie;
While (thingie = [enumerator nextObject]) {
NSLog (@ "thingie: % @", thingie );
    }
// 2,-(NSEnumerator *) reverseObjectEnumerator; // forward from the back
// NSMutableArray * array = [NSMutableArray arrayWithObjects:
@ "One", @ "Two", @ "Three", nil];
NSEnumerator * enumerator;
Enumerator = [array reverseObjectEnumerator];

Id object;
While (object = [enumerator nextObject]) {
NSLog (@ "object: % @", object );
    }
// 3. Fast enumeration
// NSMutableArray * array = [NSMutableArray arrayWithObjects:
@ "One", @ "Two", @ "Three", nil];
For (NSString * string in array)
    {
NSLog (@ "string: % @", string );
    }

----- NSValue (encapsulate any object )-----
// Put NSRect into NSArray
NSMutableArray * array = [[NSMutableArray alloc] init];
NSValue * value;
CGRect rect = CGRectMake (0, 0,320,480 );
Value = [NSValue valueWithBytes: & rect objCType: @ encode (CGRect)];
[Array addObject: value];
NSLog (@ "array: % @", array );
// Extract from Array
Value = [array objectAtIndex: 0];
[Value getValue: & rect];
NSLog (@ "value: % @", value );

----★Use NSMutableArray to prevent memory leakage★------
NSObject * p1 = [[NSObject alloc] init];
NSObject * p2 = [[NSObject alloc] init];
NSMutableArray * objectsArray = [[NSMutableArray alloc] init];

[ObjectsArray addObject: p1];
NSLog (@ "p1 count: % d", [p1 retainCount]); // output 2, that is, after the append object is executed, the object counter is also added with 1
// [P1 release];
// NSLog (@ "p1 count: % d", [p1 retainCount]);

// When array replacement is also performed
[ObjectsArray replaceObjectAtIndex: 0 withObject: p2];
NSLog (@ "p2 count: % d", [p2 retainCount]); // output 2, also 2
NSLog (@ "p1 count: % d", [p1 retainCount]); // output 1, object p1 still exists
// [P2 release];
// NSLog (@ "p2 count: % d", [p2 retainCount]);

// Execute clearing the array
[ObjectsArray removeAllObjects];
NSLog (@ "p2 count: % d", [p2 retainCount]); // output 1, object p2 still exists
// [P2 release];

It can be seen that after each execution of the preceding array operation, the object release, such as the statement in the preceding comment, must be executed to ensure that the memory is not leaked.


NSSet
Unordered collection of objects.
Immutable. You cannot add or remove objects to it once it's created.
Important methods:
+ SetWithObjects :( id) firstObj,...; // nil terminated

-(Int) count;
-(BOOL) containsObject :( id) anObject;
-(Id) anyObject;
-(Void) makeObjectsPerformSelector :( SEL) aSelector;
-(Id) member :( id) anObject; // uses isEqual: and returns a matching object (if any)

NSMutableSet
Mutable version of NSSet.
+ (NSMutableSet *) set;
-(Void) addObject :( id) anObject;
-(Void) removeObject :( id) anObject;
-(Void) removeAllObjects;
-(Void) unionSet :( NSSet *) otherSet;
-(Void) minusSet :( NSSet *) otherSet;
-(Void) intersectSet :( NSSet *) otherSet;

NSDictionary
Key-value, key-value,... a series of key-value pairs.
The key is unique in the entire dictionary. You can use the key to query one or more values ).
Hash table. Look up objects using a key to get a value.
Immutable. You cannot add or remove objects to it once it's created.
Keys are objects which must implement. Keys are usually NSString objects.
-(NSUInteger) hash &-(BOOL) isEqual :( NSObject *) obj
Important methods:
+ DictionaryWithObjectsAndKeys: (id) firstObject ,...;
-(Int) count;
-(Id) objectForKey :( id) key;
-(NSArray *) allKeys;
-(NSArray *) allValues;
----- Create a dictionary -----
//-(Id) initWithObjectsAndKeys;
// NSDictionary * dictionary = [[NSDictionary alloc] initWithObjectsAndKeys: @ "One", @ "1", @ "Two", @ "2", @ "Three ", @ "3", nil];
NSString * string = [dictionary objectForKey: @ "One"];
NSLog (@ "string: % @", string );
NSLog (@ "dictionary: % @", dictionary );
[Dictionary release];

NSMutableDictionary
Mutable version of NSDictionary.
+ (NSMutableDictionary *) dictionary;
-(Void) setObject :( id) anObject forKey :( id) key;
-(Void) removeObjectForKey :( id) key;
-(Void) removeAllObjects;
-(Void) addEntriesFromDictionary :( NSDictionary *) otherDictionary;
----- Create a variable dictionary -----
// Create
NSMutableDictionary * dictionary = [NSMutableDictionary dictionary];
// Add a dictionary
[Dictionary setObject: @ "One" forKey: @ "1"];
[Dictionary setObject: @ "Two" forKey: @ "2"];
[Dictionary setObject: @ "Three" forKey: @ "3"];
[Dictionary setObject: @ "Four" forKey: @ "4"];
NSLog (@ "dictionary: % @", dictionary );
// Delete the specified Dictionary
[Dictionary removeObjectForKey: @ "3"];
NSLog (@ "dictionary: % @", dictionary );

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.