在XCode4.2以上的版本为ARC(自动引用计数)也就是会自动释放不需要的内存
所有在Xcode4.2以上的版本使用MRC得在
在文本框里的大上-fno-objc-arc
#import "ViewController.h"
#import "Student.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
NSMutableArray *array1 = [NSMutableArrayarray];
NSMutableArray *array2 = [NSMutableArrayarray];
[array1 addObject:array2];
[array2 addObject:array1];
//上面这个测试重复引用
//下面测试内存泄露
Student *student1=[[Studentalloc]init];
NSLog(@"count1=%lu",(unsignedlong)[student1 retainCount]);
Student *student2=[[Studentalloc] init];
NSLog(@"count2=%lu",(unsignedlong)[student2 retainCount]);
[student1 release];
NSLog(@"count1=%lu",(unsignedlong)[student1 retainCount]);
Student *student3=[student2 copy];
NSLog(@"count3=%lu",(unsignedlong)[student3 retainCount]);
if (student2 == student3)
{
NSLog(@"相同");
}
Student *student4=[student2 mutableCopy];
NSLog(@"count5=%lu",(unsignedlong)[student4 retainCount]);//等于1
NSString *string=[NSStringstringWithFormat:@"ppp"];
NSString *string1=[string copy];
if (string == string1)
{
NSLog(@"%lu,%lu",(unsignedlong)[string retainCount],[string1retainCount]);
}
NSMutableString *mstring=[NSMutableStringstringWithFormat:@"ddd"];
NSMutableString *mstring1=[mstring copy];
NSLog(@"%lu,%lu",(unsignedlong)[mstring retainCount],[mstring1retainCount]);
//当我们将一个对象加入到集合(如数组,字典和set集合)中时,集合会拥有该对象的所有权,当集合移除该对象
//或者集合本身被清理是,集合会放弃对象的所有权
NSMutableArray *array=[NSMutableArrayarray];
for (int i=0; i<10; i++)
{
Student *stu=[Studentnew];
[array addObject:stu];
[stu release];
}
Student *st=[Studentnew];
[st release];
NSLog(@"%lu",(unsignedlong)[st retainCount]);//本来预期输出是0为什么在这里会输出1呢
//已经释放的对象发送NSLog发送了一个消息
//在最后一次执行马上就要回收和就没有必有-1了不减1加快对象的释放
[student2 release];
[student3 release];
[student4 release];
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
在上面的代码通过Xcode->最上面的导航栏Product->Profile
会看的这张图片右边的图标
然后选择第二行第六个叫“Leaks”用来测试重复调用和内存泄露