Arrays in OC are quite different from those in C, C ++, or Java.
Arrays in foundation are a set of ordered objects. arrays cannot store basic data types, but can only store class instances (objects ), to store basic data types and struct in an array, encapsulate them first.
Nsarray immutable Array
Single element Initialization
// Initialize a single-element array nsarray * array = [nsarray arraywithobject: @ "one"]; nslog (@ "% @", array); // initialize a multi-element array, note that an additional S nsarray * array2 = [nsarray arraywithobjects: @ "one", @ "two", @ "three", nil] is added to the comparison above. nslog (@ "% @", array2); // initialize a multi-element array nsarray * array3 = [[nsarray alloc] initwithobjects: @ "you", @ "me ", @ "he", nil]; nslog (@ "% @", array3); // copy an array nsarray * array4 = [[nsarray alloc] initwitharray: array3]; nslog (@ "% @", array4); // obtain the number of elements in the array nsinteger * COUNT = [array4 count]; nslog (@ "% d", count ); // print 3 // Access Object nsstring * firstobj = [array4 objectatindex: 2]; nslog (@ "% @", firstobj); // print he
// Append an object to the original array and generate a new array
Nsarray * array5 = [array4arraybyaddingobject: @ "it"];
Nslog (@ "% @", array5 );
// Use the specified string to connect the elements of the array
Nsstring * arraystring = [array5componentsjoinedbystring: @ "/"];
Nslog (@ "% @", arraystring); // print you/ME/he/it
// Whether the array contains an object
Bool iscontain = [array5
Containsobject: @ "it"];
Nslog (@ "% d", iscontain); // print 1
// Query the position of the object in the array
Nsinteger * atindex1 = [array5
Indexofobject: @ "it"];
Nsinteger * atindex2 = [array5
Indexofobject: @ "YY"];
Nslog (@ "at % d", atindex1); // print at 3
Nslog (@ "at % d", atindex2); // print does not exist
2. variable array nsmutablearray
Inherited from nsarray, so all nsarray methods can be used.
// Add an element nsmutablearray * array1 = [nsmutablearray arraywithobject: @ "hello"]; [array1 addobject: @ "world"]; nslog (@ "% @", array1); // Add the element [array1 insertobject: @ "nihao" atindex: 0] to the specified subscript of the array; nslog (@ "% @", array1 ); // Delete the element [array1 removeobjectatindex: 0]; nslog (@ "% @", array1); // Delete the last element [array1 removelastobject]; nslog (@ "% @", array1); // Add the array [array1 addobjectsfromarray: array1] to the array; nslog (@ "% @", array1 ); // Replace the specified position element [array1 replaceobjectatindex: 1 withobject: @ "world"]; nslog (@ "% @", array1 );
Traverse Arrays
Nsarray * array2 = [nsarray arraywithobjects: @ "one", @ "two", @ "three", @ "four", @ "five", nil]; for (INT I = 0; I <[array2 count]; I ++) {nsstring * element = [array2 objectatindex: I]; nslog (@ "% @", element);} // method 2, enumeration method for (nsstring * element in array2) {nslog (@ "% @", element );}