#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"1================");
堆区
NSString * str=[[NSString alloc] initWithFormat:@"%@",@"qqq"];
//NSString * str=[NSString stringWithFormat:@"%@",@"qqq"];这两个效果一样
NSLog(@"%li",[str retainCount]);//1
NSLog(@"%p",str);//0x100201fa0
[str retain];
NSLog(@"%li",[str retainCount]);//2
[str release];
NSLog(@"%li",[str retainCount]);//1
[str release];
NSLog(@"%li",[str retainCount]);//悬垂指针,内存已经释放,指针指向已经释放的内存 1152921504606846975
NSLog(@"%p",str);//不是很清楚,地址仍然可以访问,指向对象的指针仍然被保留在str中,能够访问
}
//NSLog(@"%p",str);
NSLog(@"3================");
NSString * str11=nil;//当一个对象的引用计数为0时,系统会自动销毁该对象
NSLog(@"%li",[str11 retainCount]);//0
NSLog(@"%p",str11);//0x0
[str11 retain];
NSLog(@"%li",[str11 retainCount]);//0
[str11 release];
NSLog(@"%li",[str11 retainCount]);//0
[str11 release];
NSLog(@"%li",[str11 retainCount]);//0
NSLog(@"%p",str11);//0x0
NSLog(@"4================");
NSString * str22=@"qqq";
//等价于NSString * str=[[NSString alloc]initWithString:@"qqq"];
[str22 retain];
NSLog(@"%li",[str22 retainCount]);//-1,retain与release不起作用
[str22 release];
NSLog(@"%li",[str22 retainCount]);//-1
[str22 release];
NSLog(@"%li",[str22 retainCount]);//-1
//[str22 dealloc];,不是很清楚,就是说你malloc分配的内存赋值给了一个已经被释放的指针(此指针已不存在),系统会自动管理,不用手动管理
NSString * str1=@"222";
//NSString * str4=[NSString stringWithString:@"222"];Xcode4.4以后,已经放弃使用
NSLog(@"%li",[str1 retainCount]);//-1
NSLog(@"--%p",str1);
NSString *str2=[[NSString alloc]initWithString:@"222"];
NSLog(@"%li",[str2 retainCount]);//-1
NSLog(@"--%p",str2);//前两个地址一样0x100001068,字符串都在文字常量区,不在栈上,说明Xcode做了优化,retain与release不起作用
NSString *str3=[[NSString alloc]initWithFormat:@"%@",@"222"];
NSLog(@"%li",[str3 retainCount]);//-1
NSLog(@"--%p",str3);
NSString * str5=[NSString stringWithFormat:@"%@",@"222"];
NSLog(@"%li",[str5 retainCount]);//-1
NSLog(@"--%p",str5);//后两个地址一样,在堆区,0x7fff7ce4e640,至于这两个的引用计数,真的搞不懂
return 0;
}