Objective-c Study 07-nsarray and Nsmutablearray

Source: Internet
Author: User
Outline

NSArray

NSMutableArray

Quick enumeration

 

 NSArray

NSArray is a static array, that is, an immutable array.Once created, you cannot add, delete, or modify elements in it. NSArray inherits from NSObject and is used to manage a collection of ordered objects. (C), as in C, the index of the elements in the array starts from 0. The array can be used to store objects of the same class, or objects of different classes. But You cannot store nil, nil is considered as the end of the array, and the system will automatically generate it at the end of the method.

Remember: NSArray can only store data of object type, and cannot store basic data types in C language, such as int, float, etc .;

NSArray common methods

Create

    1. Create an empty array init

便利 Convenience constructor method array

NSArray * arr = [[NSArray alloc] init];
NSArray * arr0 = [NSArray array];
Note: Once an immutable array is created, its contents can no longer be modified, but its array pointer can be changed and re-pointed. There is no content in the empty array after it is created.

2. Create an array of own objects initWithObjects:

NSArray * arr = [[NSArray alloc] initWithObjects: @ "a", @ "b", @ "c", nil];
NSLog (@ "% @", arr);
Convenient constructor method to create array arrayWithObjects:

NSArray * arr1 = [NSArray arrayWithObjects: @ "d", @ "e", @ "f", nil];
NSLog (@ "% @", arr1);
3. Initialize and return a new array with the objects in the existing array initWithArray:

NSArray * arr3 = [[NSArray alloc] initWithArray: arr];
NSLog (@ "% @", arr3);
Convenient constructor method arrayWithArray:

NSArray * arr4 = [NSArray arrayWithArray: arr1];
NSLog (@ "% @", arr4);
4. Access

// return the elements in the array count
NSUInteger count = arr1.count; // arr1.count is equivalent to [arr1 count]
NSLog (@ "count =% lu", count);

// access the first element in the array firstObject
NSString * firstObject = arr1.firstObject;

// access the last element in the array lastObject
NSString * lastObject = arr1.lastObject;
NSLog (@ "fistObject =% @ lastObject =% @", firstObject, lastObject);

// Return the elements in the array according to the index objectAtIndex:
NSString * str = [arr objectAtIndex: 0];
NSLog (@ "% @", str);
5.sortedArrayUsingSelector: (SEL) comparator

ArrayThe sort method of NSArray will return a new array.The new array is an array in which the elements in the old array are sorted by the selector.

NSArray * array = [NSArray arrayWithObjects: @ "4", @ "1", @ "5", @ "2", @ "3", nil];
NSArray * sortArray = [array sortedArrayUsingSelector: @selector (compare :)];
NSLog (@ "% @", sortArray);
Print result:

     2015-11-29 19: 43: 36.314 Myself [804: 76839] (
     1,
     2,
     3,
     4,
     5
     )
Use the sortedArrayUsingSelector: (SEL) comparator method to compare the objects in the array one by one, and generate a new array based on the result of the comparison.

比较 When comparing array objects, use the method specified by the selector comparator. The selector requires an input parameter and the return value is of the NSComparisonResult type.

ArrayNSArray * newArray = [anArray sortedArrayUsingSelector: @selector (compare :)];

 

NSMutableArray

 

NSMutableArray variable array, inherited from NSArray, so it can use all methods defined in NSArray. The content stored in NSMutableArray array can be changed, add delete replace

Create

InitWithCapacity: <# (NSUInteger) #> (NSInteger specifies the length of the array)

Convenient constructor method arrWithCapacity: <# (NSUInteger) #>

NSMutableArray * mArr = [[NSMutableArray alloc] initWithCapacity: 0];
NSMutableArray * mArr2 = [NSMutableArray arrayWithCapacity: 0];
Add

1. Add elements to the end of the variable array addObject:

[mArr addObject: @ "HarbingWang"];
2. Add all elements in other arrays to the end of the array addObjectsFromArray:

例如 // For example: The following array insertArray exists, add it to the empty array mArr2 created above

NSArray * insertArray = [NSArray arrayWithObjects: @ "Manager", @ "productDog", @ "marketMonkey", @ "operationMouse", @ "serviceCattle", @ "programmingApe", @ "designLion", nil];

[mArr2 addObjectsFromArray: insertArray];
 NSLog (@ "% @", mArr2);
Print result:

     2015-11-29 20: 17: 21.708 Myself [836: 94080] (
     Manager,
     productDog,
     marketMonkey,
     operationMouse,
     serviceCattle,
     programmingApe,
     designLion
     )
3. Add element to the specified position insertObject: atIndex:

[mArr2 insertObject: @ "ziChaoZhe" atIndex: 6];
 NSLog (@ "% @", mArr2);
    print

     2015-11-29 20: 21: 19.615 Myself [879: 95624] (
     Manager,
     productDog,
     marketMonkey,
     operationMouse,
     serviceCattle,
     programmingApe,
     ziChaoZhe,
     designLion
     )
     * It can be known from the print result: insertObject: is to add anObject to the specified index position, and the subsequent elements are shifted back in order.The index must be between 0 and the range of the array.

4. Exchange two elements in an array exchangeObjectAtIndex: <# (NSUInteger) #> withObjectAtIndex: <# (NSUInteger) #>

 [mArr2 exchangeObjectAtIndex: 0 withObjectAtIndex: 1];
5. Delete

5. Remove the element at the specified position in the array removeObjectAtIndex:
[mArr2 removeObjectAtIndex: 1];

6. Delete the specified object. If it is found, it will be deleted. If it is not found, it will not be deleted.
[mArr2 removeObject: @ "Manager"];

7. Remove the last element removeLastObject
[mArr2 removeLastObject];

8. Remove all elements from the array removeAllObjects
[mArr2 removeAllObjects];
9 sortUsingSelector:

[mArr2 sortUsingSelector: @selector (compare :)];
NSLog (@ "% @", mArr2);
Print:

     2015-11-29 20: 51: 12.980 Myself [1013: 107642] (
     designLion,
     marketMonkey,
     operationMouse,
     productDog,
     programmingApe,
     serviceCattle,
     ziChaoZhe
     )
 

 

Quickly enumerate forin

OC provides a syntax for traversing container classes (arrays, dictionaries, collections, etc.), called fast enumeration, which is an enhanced for loop. When using this syntax, you don't need to care about the number of elements in the collection. , We usually call it forin syntax. The syntax is as follows:

     for (<#type * object #> in <# collection #>) {

     <# statements #>

     }

     parameter:

     <#type * object #>: the object type in the collection pointer variable of the object type

     <# collection #>: collection object name

     <# statements #>: loop body (corresponding processing)

     Benefit: Fast enumeration (enhanced for loop) provided by OC, no need to care about the number of elements in the collection

     Execution steps: Each time the loop takes out the elements of the collection and assigns them to pointer variables

It is especially worth noting: During the fast enumeration process, the elements in the collection cannot be modified, so do not add operations that can cause the collection to change in the loop body, otherwise the system will throw an exception

The order of traversing the elements in the container is related to the type of the container. If it is an array type, it will be traversed from the beginning, and if it is a collection or a dictionary, the order of traversal is related to the internal implementation of the container. It will be covered later.

for (NSString * string in mArr2) {
     // [mArr5 removeObject: string]; // If you write this way, the system will report an error: was mutated while being enumerated The content in the collection was modified during fast enumeration, which will cause Crash
     NSLog (@ "% @", string);
}
Print

2015-11-29 21: 01: 16.206 Myself [1022: 111865] designLion
2015-11-29 21: 01: 16.206 Myself [102
2: 111865] marketMonkey
2015-11-29 21: 01: 16.220 Myself [1022: 111865] operationMouse
2015-11-29 21: 01: 16.220 Myself [1022: 111865] productDog
2015-11-29 21: 01: 16.220 Myself [1022: 111865] programmingApe
2015-11-29 21: 01: 16.220 Myself [1022: 111865] serviceCattle
2015-11-29 21: 01: 16.221 Myself [1022: 111865] ziChaoZhe
When beginners use this syntax, the more difficult is how to write the first parameter <#type * object #> and the second parameter <# collection #>?

Here, <#type * object #> is a variable.Because forin takes out the elements in the collection to be traversed in order to assign to this pointer variable, the type of this variable must be the same as the type of the object in the collection. Keep the same, for example, the elements in the array mArr2 in the above example are all strings of NSString type, so you should use an array variable string to receive it. If it is a Person object variable, you must use a Person * type variable to store it. ... and <# collection #> is a collection to traverse, which is easy to understand.

Objective-C Learning Article 07—NSArray and NSMutableArray
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.