NSMutableArray

简介: Student.h: #import @interface Student : NSObject@property(nonatomic,assign) int age;+(id)studentWithAge:(int)age;@end Student.

Student.h:

#import <Foundation/Foundation.h>

@interface Student : NSObject
@property(nonatomic,assign) int age;
+(id)studentWithAge:(int)age;
@end

Student.m:

#import "Student.h"

@implementation Student
+(id)studentWithAge:(int)age{
    Student *stu=[[[Student alloc] init] autorelease];
    stu.age=age;
    return stu;
}
-(void)dealloc{
    NSLog(@"Age=%i对象被释放",_age);
    [super dealloc];
}
@end

main:

#import <Foundation/Foundation.h>
#import "Student.h"
void arrayCreate(){
    NSMutableArray *array=[NSMutableArray arrayWithObject:@"1"];
    //添加成员
    [array addObject:@"2"];
    [array addObject:@"3"];
    //删除成员
    [array removeObject:@"2"];
    [array removeLastObject];
    [array removeAllObjects];
    
    NSLog(@"动态数组是:%@",array);
}
#pragma mark - 数组内存的管理
void arrayMemory(){
    NSMutableArray * array=[NSMutableArray array];
    Student *stu1=[Student studentWithAge:16];
    Student *stu2=[Student studentWithAge:22];
    //注意:array进行添加元素的时候,会对被添加的元素执行一次retain操作,计数器加1
    [array addObject:stu1];//注意:执行这句话之后,首先先对stu1进行一次retain操作,计数器加1
    [array addObject:stu2];
    NSLog(@"addStu->计数器%i",[stu1 retainCount]);
    //注意:array进行删除元素的时候,会对被删除的元素执行一次release操作,计数器减1
    [array removeObject:stu1];//执行这句之后,stu1进行一次release操作,计数器减1
    NSLog(@"removeStu->计数器%i",[stu1 retainCount]);
    //注意:当数组被释放的时候,会对有所由成员进行一次release操作
}
#pragma mark - 替换元素
void arrayReplase(){
    NSMutableArray *array=[NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"4",nil];  //只能塞OC对象
    //替换元素
    [array replaceObjectAtIndex:1 withObject:@"8"];
    Student *stu1=[Student studentWithAge:16];
    [array replaceObjectAtIndex:2 withObject:stu1];//随便塞对象,可以替换一个stu对象
    NSLog(@"array:%@",array);
}
#pragma mark - 排序
void arraySort(){
    NSMutableArray *array=[NSMutableArray arrayWithObjects:@"1",@"4",@"3",@"2",nil];  //只能塞OC对象
    NSLog(@"排序前:%@",array);
    [array sortUsingSelector:@selector(compare:)];
    NSLog(@"排序后:%@",array);
    
}
int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        /*arrayCreate();
        arrayMemory();
        arrayReplase();*/
        arraySort();
    }
    return 0;
}

结果:

2013-08-02 15:32:46.883 NSMutableArray[1179:303] 排序前:(

    1,

    4,

    3,

    2

)

2013-08-02 15:32:46.885 NSMutableArray[1179:303] 排序后:(

    1,

    2,

    3,

    4

)


相关文章
|
XML 数据格式
|
机器学习/深度学习 C语言 索引
|
存储 Android开发 自然语言处理