NSMutableArray -- variable array, nsmutablearray --
//// Main. m // OC04-task-08 // Created by keyzhang on 15-1-24. // Copyright (c) 2015 keyzhang. all rights reserved. // # import <Foundation/Foundation. h> # import "Person. h "int main (int argc, const char * argv []) {@ autoreleasepool {// insert code here... /////////// NSMutableArray -- variable array ////////// // use the constructor of the parent class to construct a variable. array NSMutableArray * arr = [NSMutableArray array]; // NSMutableArray's own constructor, indicating the size of the initialized array. Note: This is only for code readability. NSMutableArray * arr0 = [NSMutableArray arrayWithCapacity: 2]; // Add an element (object)/* Inserts a given object at the end of the array. */[arr0 addObject: @ "1"]; [arr0 addObject: @ "2"]; [arr0 addObject: @ "3"]; NSLog (@ "arr0 is % @", arr0); // construct NSMutableArray * arr1 = [NSMutableArray arrayWithObjects: @ "1", @ "3 ", nil]; NSLog (@ "arr1 is % @", arr1); // Add a new element to the end of the array [arr addObject: @ "x"]; NSLog (@ "arr is % @", arr); // Insert the element [arr1 insertObject: @ "2" atIndex: 1]; [arr1 insertObject: @ "0" atIndex: 0]; NSLog (@ "arr1 is % @", arr1); // delete an element // Delete the last element [arr1 removeLastObject]; NSLog (@ "arr1 is % @", arr1); // Delete the specified subscript element [arr1 removeObjectAtIndex: 1]; NSLog (@ "arr1 is % @", arr1 ); // Delete the specified Element // If the element does not exist, nothing will be done [arr1 removeObject: @ "2"]; NSLog (@ "arr1 is % @", arr1 ); // remove all elements [arr1 removeAllObjects]; NSLog (@ "arr1 is % @", arr1); // Add multiple elements NSMutableArray * arr2 = [NSMutableArray arrayWithObjects: @ "1", @ "2", nil]; NSArray * lists = @ [@ "3", @ "4", @ "5", @ "6"]; [arr2 addObjectsFromArray: lists]; NSLog (@ "arr2 is % @", arr2 ); // replace and exchange elements // Replace the target object [arr2 replaceObjectAtIndex: 2 withObject: @ "7"] based on the passed object; NSLog (@ "arr2 is % @", arr2); // exchange the element based on the subscript of the two elements [arr2 exchangeObjectAtIndex: 2 withObjectAtIndex: 5]; NSLog (@ "arr2 is % @", arr2); // Extension: Person * ps = [[Person alloc] init]; ps. name = @ "tom"; ps. age = 10; // array traversal NSArray * arr3 = @ [@ "1", @ "2", @ "3", @ "4", @ "5 ", @ "6", @ "7", ps]; // traditional Traversal method for (int I = 0; I <[arr3 count]; I ++) {NSLog (@ "arr3 [% d] is % @", I, arr3 [I]);} // fast Traversal method for (id value in arr3) {// loop block if ([value isMemberOfClass: [Person class]) {Person * ps = (Person *) value; NSLog (@ "person name is % @", ps. name); continue;} NSLog (@ "value is % @", value);} // mutableCopy NSArray * arr4 = @ [@ "1", @ "2 ", @ "3"]; NSLog (@ "arr4 is % @", arr4); NSMutableArray * arr5 = [arr4 mutableCopy]; [arr5 addObject: @ "4"]; NSLog (@ "arr5 is % @", arr5); // NSMutableArray * arr6 = [NSMutableArray arrayWithArray: arr4];} return 0 ;}