// // main.m // OC9_字符串的内存管理 // // Created by zhangxueming on 15/6/18. // Copyright (c) 2015年 zhangxueming. All rights reserved. // #import <Foundation/Foundation.h> //字符串内存管理, retainCount的值可以不参考, 只需要遵守内存管理法则就行 int main(int argc, const char * argv[]) { @autoreleasepool { NSString *str1 = @"hello world"; NSLog(@"str1 retainCount = %li", str1.retainCount); NSString *str2 = [NSString stringWithString:str1]; NSLog(@"str2 retainCount = %li", str2.retainCount); NSString *str3 = [[NSString alloc] initWithString:str1]; NSLog(@"str3 retainCount = %li",str3.retainCount); NSLog(@"str1 = %p str2 = %p str3 = %p", str1, str2, str3); [str3 release]; NSString *str4 = [str3 retain]; NSLog(@"str4 retainCount = %li", str4.retainCount); [str4 release]; NSString *str5 = [str4 copy]; NSLog(@"str5 retainCount = %li", str5.retainCount); NSLog(@"str5 = %p str4 = %p", str5, str4); [str5 release]; NSMutableString *mulStr1 = [[NSMutableString alloc] initWithString:str5]; NSLog(@"mulStr1 retainCount = %li", mulStr1.retainCount); NSLog(@"mulStr1 = %p str5 = %p", mulStr1, str5); NSMutableString *mulStr2 = [mulStr1 retain]; NSLog(@"mulStr2 retainCount = %li", mulStr2.retainCount); NSString *str6 = [[NSString alloc] initWithString:mulStr1]; NSLog(@"str6 retainCount = %li", str6.retainCount); NSString *str7 = [[NSString alloc] init];//@"" NSLog(@"str7 retainCount = %li", str7.retainCount); NSLog(@"str6 = %p str7 = %p", str6, str7); NSString *str8 = [str7 stringByAppendingString:@"qian feng"]; NSLog(@"str8 retainCount = %li", str8.retainCount); NSLog(@"str8 = %p", str8); [str6 release]; [str7 release]; [mulStr1 release]; [mulStr2 release]; } return 0; }
时间: 2024-10-11 05:14:17