关于objective-c的内存管理问题
内存管理总是搞不清楚,,写了个实例,,哪位打下帮忙看看怎样释放函数中的对象:-(NSString*)cmdExcute:(NSString*)cmdparaMeter:(...
内存管理总是搞不清楚,,写了个实例,,哪位打下帮忙看看怎样释放函数中的对象:
-(NSString*)cmdExcute:(NSString*)cmd paraMeter:(NSArray*)para{
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:cmd];
NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
NSFileHandle *file = [pipe fileHandleForReading];
[task setArguments:para];
[task launch];
NSData *data = [file readDataToEndOfFile];
NSString *string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSString * ret = [NSString string];
string = nil;
[string release];
NSLog(@"data retain :%lx", [data retainCount]);
data = nil;
[data release];
NSLog(@"file retain :%lx", [file retainCount]);
file = nil;
[file release];
NSLog(@"task retain :%lxyixiatai111", [file retainCount]);
task = nil;
[task release];
NSLog(@"pipe retain :%lx", [pipe retainCount]);
pipe = nil;
[pipe release];
return ret;
} 展开
-(NSString*)cmdExcute:(NSString*)cmd paraMeter:(NSArray*)para{
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:cmd];
NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
NSFileHandle *file = [pipe fileHandleForReading];
[task setArguments:para];
[task launch];
NSData *data = [file readDataToEndOfFile];
NSString *string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSString * ret = [NSString string];
string = nil;
[string release];
NSLog(@"data retain :%lx", [data retainCount]);
data = nil;
[data release];
NSLog(@"file retain :%lx", [file retainCount]);
file = nil;
[file release];
NSLog(@"task retain :%lxyixiatai111", [file retainCount]);
task = nil;
[task release];
NSLog(@"pipe retain :%lx", [pipe retainCount]);
pipe = nil;
[pipe release];
return ret;
} 展开
2个回答
展开全部
我去。。得先release 再nil
[string release];
string = nil;
[task release];
task = nil;
[string release];
string = nil;
[task release];
task = nil;
追问
囧哦,,再请教一下,还是上边那个例子,把NSString做返回值,那个NSString还需要做释放处理吗吗?是不是需要autorelease?
追答
如果是通过 alloc ,new,copy 创建的话返回时都要autorelease的.ret不是以上创建方式创建的,所以已经是一个autorelease类型了,返回时不用加了。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询