• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Yesi-悦思
"(program(computers) == *art) ? so : what" 修身岂为名传世,作事惟思利及人
博客园    首页    新随笔    联系   管理    订阅  订阅

NSMutableArray

NSMutableArray 是一个可变数组,是NSArray的子类,但是不可以添加空值

创建NSMutableArray的方法

+(id)arrarWithCapacity:(NSInteger)numItems

-(id)initWithCapacity:(NSInteger)numItems

也可以用创建NSArray的方法创建NSMutableArray

当一个元素被加到集合中时,会执行一次retain操作;当一个元素从集合中移除时,会执行一次release操作,当集合被销毁时(dealloc),集合里面所有元素都执行一次release操作(这个原则同样适用于其它集合:NSDictionary\NSSet)


void arrayCreate(){

NSMutableArray *array=[NSMutableArray arrayWithObject:@“1”];

//Add elements

[array addObject:@”2”];

[array addObject:@”3”];

//removement

[array removeObject:@”2”];

[array removeLastObjects];

[array removeallobjects];

image

NSLog(@”%@”,array);

}

#pragma mark memory management

Student.h

@interface Student:NSObject

@property (nonatomic,assign) int age;

+(id)studentWithAge: (int) age;

@end

Student.m

@implemtation Student

+(id)studentWithAge: (int) age{

Student *stu= [[[Student alloc]init]autorelease];

stu.age=age;

return stu;

}

-(void)dealloc{

NSLog(@”age=%i is destroied”,_age);

[super dealloc];

}

 

@end

main.m

#import ”Student.h”

void arraymemory(){

NSMutableArray *arry=[NSMutableArray array];

Student *stu1=[Student studentWithAge:10];

Student *stu2=[Student studentWithAge:20];

[array addObject:stu1];

[array addObject:stu2];

NSLog(@”%zi”,[stu1 retainCount]);

//stu1,stu2 counter 2

[array removeObject:stu1];//stu1 counter1, stu2 counter 2

NSLog(@”%zi”,[stu1 retainCount]);

}


设置集合元素

-(void)setArray:(NSArry *)otherArray

添加一个元素

-(void)addobject:(id)anObject

添加otherArray的全部元素到集合中

-(void)addObjectsFromArray:(NSArray *)otherArray

插入一个对象,在Index地方插入一个对象

-(void)insertObjects:(id)anObject atIndex:(NSUInteger)index

在Indexs指定位置分别插入Objects中的元素

-(void)insertObjects;(NSArray *) objects atIndexs:(NSInsexSet *)indexs


#pragma mark replace elements

void arrayReplace(){

NSMutableArray *array=[NSMutableArray arrayWithObjects:@“1”,@”2”,@”3”,nil];

[array replaceObjectAtIndex:1 withObject:@”4”];//143
}


#pragma mark sort

void arrayort(){

NSMutableArray *array=[NSMutableArray arrayWithObjects:@“1”,@”3”,@”2”,nil];

[array sortUsingSelector:(compare:)];//因为是可变数组所以没有返回值

NSLog(@”%@”,array);

image

}

posted @ 2015-06-02 17:08  悦思  阅读(319)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3