同樣的,數組也有可變的形式,即NSMutableArray,現在我們來實現這些方法:
(1)建立Person.h檔案,實現如下:
#import <Cocoa/Cocoa.h>@interface Person : NSObject@property(nonatomic,strong) NSString *personName;- (instancetype)initWithPersonName: (NSString *)name;@end
(2)建立Person.m檔案,實現如下:
#import "Person.h"@implementation Person//重寫init方法;- (instancetype)initWithPersonName: (NSString *)name{ self = [super init]; if (self) { _personName = name; } return self;}@end
(3)在main.m中實現如下:
#import <Foundation/Foundation.h>#import "Person.h"int main(int argc, const char * argv[]) { @autoreleasepool { //添加元素; Person *person1 = [[Person alloc] initWithPersonName:@"Jack"]; Person *person2 = [[Person alloc] initWithPersonName:@"Mary"]; Person *person3 = [[Person alloc] initWithPersonName:@"Robert"]; NSMutableArray *arr = [[NSMutableArray alloc] init]; [arr addObject:person1]; [arr addObject:person2]; [arr addObject:person3]; for (Person *p in arr) { NSLog(@"%@",p.personName); } Person *person4 = [[Person alloc] initWithPersonName:@"me"]; [arr addObject:person4]; for (Person *p in arr) { NSLog(@"%@",p.personName); } //////////////////////////////////////////////////////////////// //使用另一種初始化方式; NSMutableArray *arr1 = [[NSMutableArray alloc] init]; NSArray *arr3 = [[NSArray alloc] initWithObjects:person1,person2,person3, nil]; //注意下面的方法是把數組中的每一個對象作為元素來賦值給可變數組; [arr1 addObjectsFromArray:arr3]; //注意下面的方法是把整個數組作為一個對象然後來賦值給可變數組; // [arr1 addObject:arr3]; NSLog(@"%@",arr1); //刪除元素; //刪除數組內所有元素; // [arr1 removeAllObjects]; //刪除最後一個元素; // [arr1 removeLastObject]; //交換元素的位置; [arr1 exchangeObjectAtIndex:0 withObjectAtIndex:1]; NSLog(@"%@",arr1); } return 0;}
輸出結果如下:
。
github首頁:https://github.com/chenyufeng1991 。歡迎大家訪問。