утечка памяти в веб-просмотре через одну минуту только на приборе - PullRequest
1 голос
/ 12 июля 2011

это мое первое приложение для iOS, я следую документации Apple и ответам stackoverflow, в xcode мое приложение работает как на симуляторе, так и на устройстве, но на приборе утечка памяти происходит через 50 - 70 секунд после запуска приложения.

Я использую контроллер вкладок с 3 контроллерами представления, 3 веб-просмотрами, каждое веб-представление показывает веб-страницу, подобную этой:

<html dir="rtl">
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="newstyle.css" type="text/css" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/iphone.js"></script>
<title></title>
</head>
<body style="color:#FFFFFF">
<div align="center">
<table border="0" width="320" id="table1" cellspacing="5">

<tr>
<form method="get">
<input type="hidden" name="index" value="<?=$_GET['index']?>">
<input type="hidden" name="cat" value="<?=$_GET['cat']?>">
<input type="hidden" name="area" value="<?=$_GET['area']?>">
<td class="search">
<div class="back"><a href="javascript:window.history.back()">back</a></div>
    <div class="srchbox"><a href="#reviews">&nbsp;<sub>notes (<?=countDataPages('iresturant_reviews','status=1 and clientIIndex ='.$_GET['index'].' and clientID='.$_GET['id'], 1);?>)</sub></a><div id="rates"><div id="actualrates" style="width:<?=round($mydatad[7] * 10)?>%"></div></div>
</td>
</form>
</tr>
    <tr>
    <td style="padding-left: 10px; padding-right: 10px" width="265">
<div class="justBox" style="padding:10px;"> 
<b><?=unFormatData($mydata[1])?></b><br>
    <span style="font-weight: 400"><?=$catTitle[$mydata[3-$minusIndex]]?>
    <br><br>
    <?=$areaTitle[$mydata[4-$minusIndex]]?><br>
    <?=unFormatData($mydatad[3])?>
    </span>
        <p align="left" style="margin:0px;margin-top:15px;">
    <a href="page1.php?id=<?=$mydata[0]?>&index=<?=$_GET['index']?>"><img border="0" src="images/zx.png" width="40" height="40"></a>&nbsp;&nbsp;
        <a href="page2.php?id=<?=$mydata[0]?>&index=<?=$_GET['index']?>"><img border="0" src="images/xz.png" width="40" height="40"></a>
        </div></td>
    </tr>

    <tr>
    <td style="padding-left: 10px; padding-right: 10px">    
    <?
    $imgFile = 'uimages/index_'.$_GET['index'].'_'.$mydata[0].'.jpg';
    if (file_exists($imgFile))
    {
    ?>

        <img src="<?=$imgFile?>" width="100%" align="right" style="margin-left:30px;"><p>
    <?
    }
    ?></td>
    </tr>
            <tr>
    <td style="padding-left: 10px; padding-right: 10px"><br><br>
        <img border="0" src="images/phone.png" width="30" height="30" align="absmiddle"> &nbsp; <?=unFormatData($mydata[5-$minusIndex])?><br>
        <img border="0" src="images/web.png" width="30" height="30" align="absmiddle"> &nbsp; <?=unFormatData($mydatad[4])?></span>
    <br><br><?=unFormatData($mydatad[2])?>
    <p style="padding-right:10px;line-height:200%"  >
    </p><br>&nbsp;
</td>
    </tr>
<tr>
<td class="search">
    <div class="back"><a href="javascript:window.history.back()">back</a></div>
    <p style="margin-right: 10px; margin-top: 5px">
<a name="reviews"></a><font color="#FFFFFF">reviews</font>
</td>
</tr>       
<tr>
<td style="padding-left: 10px; padding-right: 10px" >
<?
    $data = getAllData('iphone_reviews','status=1 and clientIIndex ='.$_GET['index'].' and clientID='.$_GET['id'].' order by date desc');
for ($i=0; $i < sizeof($data); $i++)
{
?>  
<div class="justBox" style="padding:10px;"> 
<p style="margin:5px;"><?=unFormatData($data[$i][3])?></p>
<p dir="ltr" style="margin:0px;"><?=date("F j, Y h:i A", $data[$i][7])?></p>
<p style="margin:0px;font-weight: 400; padding:10px;"><?=unFormatData($data[$i][5])?></p>
</div>
<hr size="1">
<?
}
?>

</td>
</tr>   
<tr>
<td class="search">
    <div class="back"><a href="javascript:window.history.back()">back</a></div>
    <p style="margin-right: 10px; margin-top: 5px">
<font color="#FFFFFF">review</font>
</td>
</tr>
<tr><td style="padding-left: 10px; padding-right: 10px">
<div id="addFrm">
    <br>
    name<br>
    <input type="text" id="name" size="20" style="width:100%"><br>
    <br>
    review<br>
    <textarea rows="2" id="comment" cols="20"  style="width:100%; height:71"></textarea><br>
    <br>
    rate <?=$oTitle?><select size="1" id="rate">
    <?
    for ($i=10; $i > 0; $i--)
    {
    echo '<option value="'.$i.'">'.$i.'</option>';
    }
    ?>
    </select></span>
<span lang="ar-sy">from 10<br>
    <br>
    <button type="button" class="submitbutton" onclick="submitComment()">send</button></span></div></td></tr>   
<tr><td>&nbsp;</td></tr>    
</table>

при использовании приложения xcode> отлично работает на симуляторе и устройстве без ошибок.

с использованием инструмента> если я не делал никаких действий в веб-просмотре, то никакой утечки памяти вообще, когда я начинаю щелкать и перемещаться по веб-странице, примерно через минуту я получаю утечку памяти.

в начале я думал, что это потому, что я одновременно запускаю 3 веб-просмотра, но когда я делаю тест на 1 веб-просмотре, возникает та же проблема.

это мой код:

#import "SecondSection.h"
#import "NamesViewController.h"
#import "TypesViewController.h"
#import "AreasViewController.h"


@implementation SecondSection


- (void)loadView {
UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bk.png"]];
self.view = contentView;
[contentView release];

// Declare all three view controllers
NamesViewController *NamesInfoController = [[[NamesViewController alloc] initWithNibName:@"DetailViewController" bundle:[NSBundle mainBundle]] autorelease];

TypesViewController *typesViewController = [[[TypesViewController alloc] init] autorelease];
AreasViewController *areasViewController = [[[AreasViewController alloc] init] autorelease];

// Set a title for each view controller. These will also be names of each tab
NamesInfoController.title = @"names";
typesViewController.title = @"types";
areasViewController.title = @"areas";

NamesInfoController.tabBarItem.image = [UIImage imageNamed:@"names.png"];
typesViewController.tabBarItem.image = [UIImage imageNamed:@"types.png"];
areasViewController.tabBarItem.image = [UIImage imageNamed:@"areas.png"];


// Create an empty tab controller and set it to fill the screen minus the top title bar
UITabBarController *tabBarController = [[UITabBarController alloc] init];
tabBarController.view.frame = CGRectMake(0, 0, 320, 460);

// Set each tab to show an appropriate view controller
[tabBarController setViewControllers:
 [NSArray arrayWithObjects:NamesInfoController, typesViewController, areasViewController, nil]];

// Clean up objects we don't need anymore
[NamesInfoController release];
[typesViewController release];
[areasViewController release];

// Finally, add the tab controller view to the parent view
[self.view addSubview:tabBarController.view];    
}

- (void)dealloc
{
[super dealloc];
}

- (void)viewWillDisappear
{

}


- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
[super viewDidLoad];
}

- (void)viewDidUnload
{
[super viewDidUnload];

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

в чем проблема? мой второй вопрос и, возможно, это поможет решить первую проблему, как сделать кнопки панели вкладок, загрузить веб-представление из URL-запроса при повторном нажатии, чтобы объяснить больше: когда я впервые нажимаю кнопку панели вкладок1, она загружает контроллер view1, который загружает webview1, который загружает URL-запрос, нажимает другую кнопку панели вкладок2, затем возвращается на панель вкладок button1, он не загружает webview1 снова, он показывает его только после того, как вы его оставили, потому что панель вкладок связана с viewcontroller, а не с webview. как это исправить.

Заранее благодарим за любую помощь

ОБНОВЛЕНИЕ: @ Александр, вот пример кода из главного окна перед вторым разделом:

- (IBAction)rests:(id)sender;
{
HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.navigationController.view addSubview:HUD];
HUD.delegate = self;
HUD.labelText = @"Loading";
[HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
SecondSection *zcontroller = [[SecondSection alloc] init];
zcontroller.title = @"macaesar";
[[self navigationController] pushViewController:zcontroller animated:YES];
[zcontroller release];
}

Ответы [ 2 ]

0 голосов
/ 12 июля 2011

Macaesar попробуйте это:

1) Сделайте ваш viewcontroller делегатом вашего UIWebView.

2) Добавьте следующий метод:

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
}

Это решило мою утечку.

0 голосов
/ 12 июля 2011

Я не уверен в этой утечке в веб-просмотре, так как вы не указали способ их создания, но вам определенно нужно использовать [super loadView] в вашем классе loadView, и вы не выпускаете свой tabBarController.Я не совсем уверен, что вы использовали до класса SecondSection.Что касается загрузки webView, вы должны сделать webView переменной вашего класса, а затем использовать событие в методе UIViewController - (void) viewWillAppear: (BOOL) animated.Не забывай про супер.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...