即时通讯对于Objective-C来说相当新颖,但大部分内容都很清楚,但是当涉及到内存管理时,我会略微缩短。目前我的应用程序所做的是在NSURLConnection期间调用方法-(void)connectionDidFinishLoading:(NSURLConnection *)connection
时,我输入一个方法来解析某些数据,将其放入一个数组中,然后返回该数组。然而,我不确定这是否是最好的方法,因为我没有在自定义方法(method1,请参阅附件中的代码)中释放阵列。数组保留问题
下面是一个小脚本,用于更好地显示什么即时通讯做
.h文件中
#import <UIKit/UIKit.h>
@interface memoryRetainTestViewController : UIViewController {
NSArray *mainArray;
}
@property (nonatomic, retain) NSArray *mainArray;
@end
.m文件
#import "memoryRetainTestViewController.h"
@implementation memoryRetainTestViewController
@synthesize mainArray;
// this would be the parsing method
-(NSArray*)method1
{
// ???: by not release this, is that bad. Or does it get released with mainArray
NSArray *newArray = [[NSArray alloc] init];
newArray = [NSArray arrayWithObjects:@"apple",@"orange", @"grapes", "peach", nil];
return newArray;
}
// this method is actually
// -(void)connectionDidFinishLoading:(NSURLConnection *)connection
-(void)method2
{
mainArray = [self method1];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
mainArray = nil;
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[mainArray release];
[super dealloc];
}
@end
的,如果你只是有__ [NSArray的页头] INIT]的方式__该项目不保留既不自动释放。所以它不会被泄漏到内存中,只会在功能范围外被释放。虽然如果使用__ [带有Objects的NSArray数组:..] __,它将很容易自动释放,并且不需要在dealloc上释放它。 – Jack 2010-06-08 17:00:56
@Jack:这是无稽之谈,你拥有通过'-alloc'创建的对象。另外,将自动释放对象分配给ivars是不好的,当目前的自动释放池被耗尽时,它们将被释放,而不是当对象的生命周期结束时释放。你肯定有一些关于手动重新计数和自动释放的事情,我推荐阅读“内存管理指南”。 – 2010-06-08 18:58:54