Objective-c语言_内存管理2(代码)

来源:互联网 发布:mac pro截屏快捷键 编辑:程序博客网 时间:2024/06/07 10:47

在XCode4.2以上的版本为ARC(自动引用计数)也就是会自动释放不需要的内存


所有在Xcode4.2以上的版本使用MRC得在




=========>在文本框里的大上-fno-objc-arc


#import "ViewController.h"


#import "Student.h"


@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

 

    NSMutableArray *array1 = [NSMutableArray array];

    NSMutableArray *array2 = [NSMutableArray array];

    [array1 addObject:array2];

    [array2 addObject:array1];

    //上面这个测试重复引用

    //下面测试内存泄露

    Student *student1=[[Student alloc]init];

    NSLog(@"count1=%lu",(unsigned long)[student1 retainCount]);

    

    

    Student *student2=[[Student alloc]init];

    NSLog(@"count2=%lu",(unsigned long)[student2 retainCount]);

    

    [student1 release];

    NSLog(@"count1=%lu",(unsigned long)[student1 retainCount]);

    

    Student *student3=[student2 copy];

    NSLog(@"count3=%lu",(unsigned long)[student3 retainCount]);

    

    if (student2 == student3)

    {

        NSLog(@"相同");

    }

    

    Student *student4=[student2 mutableCopy];

    NSLog(@"count5=%lu",(unsigned long)[student4 retainCount]);//等于1

    

    NSString *string=[NSString stringWithFormat:@"ppp"];

    NSString *string1=[string copy];

    

    if (string == string1)

    {

        NSLog(@"%lu,%lu",(unsigned long)[string retainCount],[string1 retainCount]);

    }

    

    NSMutableString *mstring=[NSMutableString stringWithFormat:@"ddd"];

    NSMutableString *mstring1=[mstring copy];

    

    NSLog(@"%lu,%lu",(unsigned long)[mstring retainCount],[mstring1 retainCount]);

    

    //当我们将一个对象加入到集合(如数组,字典和set集合)中时,集合会拥有该对象的所有权,当集合移除该对象

    //或者集合本身被清理是,集合会放弃对象的所有权

    NSMutableArray *array=[NSMutableArray array];

    

    for (int i=0; i<10; i++)

    {

        Student *stu=[Student new];

        [array addObject:stu];

        [stu release];

    }

    

    Student *st=[Student new];

    [st release];

    NSLog(@"%lu",(unsigned long)[st retainCount]);//本来预期输出是0为什么在这里会输出1

    //已经释放的对象发送NSLog发送了一个消息

    //在最后一次执行马上就要回收和就没有必有-1不减1加快对象的释放

    

    

    [student2 release];

    [student3 release];

    [student4 release];

    

    

}


- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end



在上面的代码通过Xcode->最上面的导航栏Product->Profile




会看的这张图片右边的图标




然后选择第二行第六个叫“Leaks”用来测试重复调用和内存泄露


  


0 0
原创粉丝点击