Array in Objective-c

Source: Internet
Author: User



Arrays are ordered, can only hold objects, arrays have the concept of subscript (index), index elements by index, subscript starting from 0, the array is divided into non-variable groups (Nsarray) and variable arrays (Nsmutablearray).



Immutable variables Group (nsarray)



Creating an Array Object

1 // create array object
2 NSArray * arr1 = [NSArray arrayWithObjects: @ "a", @ "Apple", @ "c", nil];
3 NSLog (@ "arr1:% @", arr1);
Number of array elements

// number of elements
NSLog (@ "arr1:% lu", arr1.count);
Array element access

1 // array access
2 NSLog (@ "object:% @", [arr1 objectAtIndex: 1]);
Iterating through an array

1 // traverse the array
2 for (NSInteger i = 0; i <arr1.count; i ++) {
3 NSLog (@ "% @", [arr1 objectAtIndex: i]);
4}
Variable array (NSMultableArray)

Create array

1 // Usually create an empty container to store data objects
2 NSMutableArray * mArr = [NSMutableArray array];
3 // add element added at the end of the array
4 [mArr addObject: @ "lol"];
Insert element

1 // Insert an element according to the subscript position
2 [mArr insertObject: @ "a" atIndex: 0];
3 NSLog (@ "% @", mArr);
Delete element

1 // delete
2 [mArr removeObjectAtIndex: 0];
3 [mArr addObject: @ "abc"];
4 [mArr addObject: @ "123"];
5 [mArr addObject: @ "qwer"];
6 NSLog (@ "% @", mArr);
Replace element

1 // replace
2 [mArr replaceObjectAtIndex: 2 withObject: @ "asdf"];
3 NSLog (@ "% @", mArr);
Exchange element

1 // exchange
2 [mArr exchangeObjectAtIndex: 0 withObjectAtIndex: 3];
3 NSLog (@ "% @", mArr);
 

Objective-C arrays

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.