同样的,数组也有可变的形式,即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 。欢迎大家访问!