Nsarray is not a mutable array that can hold only objects, but may hold different types of objects
First define a class
#import <Foundation/Foundation.h>*name; -(ID) Initwithname: (NSString *) name; @end
" Person.h " @implementationperson-(ID) Initwithname: (NSString *) name { if (self =[Super init] { = name; } return Self ;} @end
Initialization of the array
//create several forms of an arrayNsarray *array = [[Nsarray alloc] INITWITHOBJECTS:P1,@"NSString",@ -, nil];//create an immutable array consisting of multiple objectsArray = [Nsarray arraywithobjects:p1,@"NSString",@ -, nil];//Engineering Mode Creation (convenience constructors) is recommended to be created in this way (no need to manage memory)NSLog (@"%@", array); ID ch[4]= {@"AAA",@"BBB",@"CC",@"DDD"}; Nsarray*array1 = [[Nsarray alloc] initwithobjects:ch count:4];//created by an arrayArray1 = [Nsarray arraywithobjects:ch count:4];//Factory modeNSLog (@"%@", array1); Nsarray*array2 = [[Nsarray alloc] init];//immutable Empty arrayArray2 =[Nsarray array]; NSLog (@"%@", array2); Array1= [Nsarray arraywithobject:@"ABC"];//Create an immutable group of objects
Common methods of array testing
//Get Array lengthNsinteger length =[array Count]; NSLog (@"%ld", length); //gets the object in the arrayID obj = [array objectatindex:0]; NSLog (@"%@", obj); //You can also use the following syntaxobj = array[0]; NSLog (@"%@", obj); //get the position of an object in an arrayNsinteger index = [array indexofobject:@ -]; NSLog (@"%lu", index); //iterating through an array//1 Conventional Way for(inti =0; i < [array count]; i++) {NSLog (@"%@", Array[i]); } //2 Fast Traversal for(ID objinchArray) {NSLog (@"%@", obj); } //convert an array to a stringNsarray *patharray = [Nsarray arraywithobjects:@" Here",@" be",@"Dragons", p1, @ -, nil]; NSLog (@"%@", [Patharray componentsjoinedbystring:@"-"]); //Array ComparisonNsarray *arrayequal1 = [Nsarray arraywithobjects:@" Here",@" be",@"Dragons", p1, @ -, nil]; Nsarray*arrayequal2 = [Nsarray arraywithobjects:@"Here1",@" be",@"Dragons", p1, @ -, nil]; NSLog (@"%HHD", [ArrayEqual1 Isequaltoarray:arrayequal2]);//result is 0 (NO)NSLog (@"%HHD", [ArrayEqual1 Isequaltoarray:arrayequal1]);//1 (YES)//Sorting of ArraysNsarray*arrsort = @[@"AAA",@"HHH",@"BBB"]; //using selectorArrsort =[Arrsort sortedarrayusingselector: @selector (compare:)]; NSLog (@"%@", Arrsort); //using blockArrsort = [Arrsort sortedarrayusingcomparator:^Nscomparisonresult (ID obj1, id obj2) {return-[(NSString *) obj1 Compare: (NSString *) OBJ2];//Reverse }]; NSLog (@"%@", Arrsort);
Introduction to OC Array method