WEB开发网
开发学院手机开发iPhone 开发 如何避免iPhone应用中内存泄露 阅读

如何避免iPhone应用中内存泄露

 2013-08-22 13:40:16 来源:WEB开发网   
核心提示:当一个集合被释放时,其中的所有对象都将被释放,如何避免iPhone应用中内存泄露(4),NSMutableArray* array = [[NSMutableArray alloc] init]; NSString* str = [[NSString alloc] initWithString:@"Bruc
当一个集合被释放时,其中的所有对象都将被释放。

NSMutableArray* array = [[NSMutableArray alloc] init];
NSString* str = [[NSString alloc] initWithString:@"Bruce Wayne"];
[array addObject: str];
[array release];
在上面的例子中,我们分配了一个数组和一个串,然后将串添加到数组中并释放数组。这使得串仅拥有一个所有者,并且在我们调用 [str release] 前它不会被释放。

用线程传递指针
在这个函数中,我们从串的 input 传递到函数 DoSomething,然后释放 input

- (void) Test
{
NSMutableString* input = [[NSMutableString alloc] initWithString:@"batman!"];
[NSThread detachNewThreadSelector:@selector(DoSomething:) toTarget:self withObject:input];
[input release];
}
detatchNewThreadSelector 增加 input 对象的引用值并在线程结束时释放它。这就是为什么我们能够在线程刚开始的时候就释放 input,而无论函数 DoSomething 何时开始或结束。

- (void) DoSomething:(NSString*)str
{
[self performSelectorOnMainThread:@selector(FinishSomething:) withObject:str waitUntilDone:false];
}
performSeclectorOnMainThread 也会保留传递的对象,直到 selector 结束。

自动释放池是特殊的线程,所以如果我们在一个新的线程上创建自动释放的对象,我们需要创建一个自动释放池来释放它们。

[NSThread detachNewThreadSelector:@selector(Process) toTarget:self withObject:nil];
这里在另一个线程上调用函数 Process

- (void) Process
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableString* output = [[[NSMutableString alloc] initWithString:@"batman!"] autorelease];
NSLog(@"output: %@", output);
[self performSelectorOnMainThread:@selector(FinishProcess) withObject:nil waitUntilDone:false];
[pool drain];
}
对象 output 被分配并且在自动释放池中设置了自动释放,它将在函数结束前被释放。

- (void) FinishProcess
{
NSMutableString* output = [[[NSMutableString alloc] initWithString:@"superman?"] autorelease];
NSLog(@"output: %@", output);
}
系统会为主线程自动创建一个自动释放池,所以在 FinishProcess 中,我们不需要为主线程上运行的函数创建自动释放池。

上一页  1 2 3 4 

Tags:如何 避免 iPhone

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接