zoukankan      html  css  js  c++  java
  • Objective-C:Foundation框架-常用类-NSMutableArray

      NSMutableArray是NSArray对的子类,它是可变的,可以随意添加或者删除元素。与Array,也有静态和动态两种创建方法。也可已使用NSArray的方法来创建NSMutableArray。当一个元素被加到NSMutableArray中时,会执行一次retain操作;当一个元素从 NSMutableArray中删除时,会执行release操作;当集合被销毁时(调用了dealloc), NSMutableArray里的所有元素都会执行一次release操作(这个原则也适用于其他集合类型:NSDictionaryNSSet等)。

    #import <Foundation/Foundation.h>
    
    @interface Student : NSObject
    @property (nonatomic, assign) int age;
    
    + (id)studentWithAge:(int)age;
    @end
    
    
    #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
    #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);
    }
    
    
    void arrayMemory() {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        // stu1:1
        Student *stu1 = [[Student alloc] init];
        stu1.age = 10;
        // stu2:1
        Student *stu2 = [[Student alloc] init];
        stu2.age = 20;
        
        // 对被添加的元素做一次retain操作,计数器+1
        [array addObject:stu1]; // stu1:2
        [array addObject:stu2]; // stu2:2
        
        NSLog(@"add->stu1:%zi", [stu1 retainCount]);
        
        // 对被删除的元素做一次release操作,计数器-1
        [array removeObject:stu1]; // stu1:1
        
        NSLog(@"remove->stu1:%zi", [stu1 retainCount]);
        
        // 释放学生
        [stu1 release]; // stu1:0
        [stu2 release]; // stu2:1
        
        // 当数组被释放的时候,会对所有的元素都做一次release操作
        [array release]; // stu2:0
    }
    
    void arrayReplace() {
        NSMutableArray *array = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", nil];
        
        [array replaceObjectAtIndex:1 withObject:@"4"];
        
        NSLog(@"%@", array);
    }
    
    void arraySort() {
        NSMutableArray *array = [NSMutableArray arrayWithObjects:@"1", @"3", @"2", nil];
        
        [array sortUsingSelector:@selector(compare:)];
        
        NSLog(@"%@", array);
    }
  • 相关阅读:
    软件工程—附加作业
    软件工程最终总结
    电梯调度(两人结对)
    VS单元测试
    第二周作业(2,3题)
    VS的安装
    补救
    漂亮男孩不说谎
    博客带我成长
    Java后缀数组-求sa数组
  • 原文地址:https://www.cnblogs.com/yif1991/p/5068147.html
Copyright © 2011-2022 走看看