[英]nsmutablearray leaking the memory iphone
我有一個nsmutablearray,我需要通過應用程序,所以我在應用程序委托中聲明它並在應用程序委托的dealloc方法中釋放它。 這是代碼。
@interface AppDelegate : UIResponder <UIApplicationDelegate>{
NSMutableArray *arr1;
IBOutlet UINavigationController *navConroller;
}
@property (strong, nonatomic) IBOutlet UIWindow *window;
@property (nonatomic, retain) UINavigationController *navConroller;
@property (nonatomic, retain) NSMutableArray *arr1;
@implementation AppDelegate
@synthesize navConroller;
@synthesize window = _window;
@synthesize arr1;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.arr1 = [[NSMutableArray alloc] init];
[self.window addSubview:navConroller.view];
[self.window makeKeyAndVisible];
return YES;
}
- (void)dealloc
{
[self.arr1 release];
[_window release];
[super dealloc];
}
當我檢查內存性能工具時,它顯示我的內存泄漏
self.arr1 = [[NSMutableArray alloc] init];
我在不同的類中使用此數組。 任何建議將不勝感激。
我在那個地方使用了Pieter Gunst的回答和泄漏停止。 但它正在另一個地方展示。 在哪里我削減json並將記錄存儲在arr1中。 這是代碼。
-(void) apiCall:(NSString *)para1 {
SBJSON *parser = [[SBJSON alloc] init];
para1 = [para1 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
para1 = [para1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *url = [[[NSString alloc] initWithFormat:@"my api url",para1] autorelease];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
arr1 = [parser objectWithString:json_string error:nil];
[json_string release];
[parser release];
}
現在泄漏顯示在下一行。
arr1 = [parser objectWithString:json_string error:nil];
有什么建議嗎?
您已分配數組,並通過訪問屬性保留它。 更改以下代碼行;
self.arr1 = [[NSMutableArray alloc] init];
任何以下任何一行..
arr1 = [[NSMutableArray alloc] init];
要么
self.arr1 = [NSMutableArray array];
要么
NSMutableArray *tArr1 = [[NSMutableArray alloc] init];
self.arr1 = tArr1;
[tArr1 release];
試試@synthesize arr1 = _arr1;
和_arr1 = [[NSMutableArray alloc] init];
正如Apurv已經提到過的那樣
self.arr1 = [NSMutableArray array];
要么
self.arr1 = [[[NSMutableArray alloc] init] autorelease];
同時使所有相同類型的屬性(不要強混合並保留):
@property (strong, nonatomic)
對於dealloc方法,使用自動生成的getter / setter:
- (void)dealloc {
self.arr1 = nil;
self.window = nil;
[super dealloc];
}
提示:
主題啟動器不使用ARC,因為
[super dealloc];
導致錯誤“ARC禁止發送'dealloc'的顯式消息”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.