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

在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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值