2011-12-26 4 views
0

내 응용 프로그램에 메모리 할당 문제가 있습니다. 이것은 얼어 붙고 결국 내 프로그램의 끝을 일으키는 것입니다. 내 코드를 검토하면 CFString에 대부분의 메모리 할당이 있음을 알았습니다. 아래는이 문제의 원인이되는 클래스입니다.할당 메모리

#import "iMAPProdutosPesquisar.h" 
#import "iMAPArrayProdutos.h" 
#import "iMAPTabela.h" 
#import "iMAPProdutosFiltro.h" 
#import "iMAPArrayAbreviatura.h" 

static NSString *dadosProdutos = nil; 

@implementation iMAPProdutosPesquisar 

@synthesize pop; 
@synthesize tv; 
@synthesize sb; 
@synthesize datBaseName; 
@synthesize datBasePath; 
@synthesize iMAP; 
@synthesize abrev; 
@synthesize opcFil; 
@synthesize cab; 
@synthesize cons; 

#define TAG_1 1 
#define TAG_2 2 
#define TAG_3 3 

#define FIRST_CELL_IDENTIFIER @"TrailItemCell" 
#define SECOND_CELL_IDENTIFIER @"RegularCell" 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { 

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 

    if (self) { 

     // Custom initialization 
    } 

    return self; 
} 

- (void)dealloc { 

    [pop release]; 
    [tv release]; 
    [sb release]; 
    [datBaseName release]; 
    [datBasePath release]; 
    [iMAP release]; 
    [abrev release]; 
    [opcFil release]; 
    [cab release]; 
    [cons release]; 
    [super dealloc]; 
} 

- (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. 
} 

#pragma mark - View lifecycle 

- (void)viewDidLoad { 

    [super viewDidLoad]; 

    // Do any additional setup after loading the view from its nib. 
    [self initDatBase]; 

    [cab setImage:[UIImage imageNamed:@"cabecalho-produtos.png"]]; 
    cab.opaque = YES; 
} 

- (void)viewDidUnload { 

    [self setPop:nil]; 
    [self setTv:nil]; 
    [self setSb:nil]; 
    [self setDatBaseName:nil]; 
    [self setDatBasePath:nil]; 
    [self setIMAP:nil]; 
    [self setAbrev:nil]; 
    [self setOpcFil:nil]; 
    [self setCab:nil]; 
    [self setCons:nil]; 
    [super viewDidUnload]; 

    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { 

    // Return YES for supported orientations 
    return (interfaceOrientation == UIInterfaceOrientationPortrait); 
} 

#pragma mark UISearchBarDelegate 

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText { 

    [self initDatBase]; 
} 

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar { 

    [searchBar resignFirstResponder]; 
} 

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar { 

    [searchBar resignFirstResponder]; 
} 

#pragma mark tableView delegates 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 

    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 

    tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine; 

    return [iMAP count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    iMAPArrayProdutos *arrayProd = (iMAPArrayProdutos *)[iMAP objectAtIndex:indexPath.row]; 

    NSString *myIdent = @"myIdent"; 

    iMAPTabela *tab = (iMAPTabela *)[tableView dequeueReusableCellWithIdentifier:myIdent]; 

    tv.autoresizesSubviews = YES; 

    if (tab == nil) { 

     tab = [[[iMAPTabela alloc] initWithFrame:CGRectZero reuseIdentifier:myIdent] autorelease]; 

     UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10.0, 0, 150.0, tableView.rowHeight)] autorelease]; 

     [tab addColumn:170]; 

     label.tag = TAG_1; 
     label.font = [UIFont systemFontOfSize:14.0]; 
     label.text = arrayProd.cod; 
     label.textAlignment = UITextAlignmentLeft; 
     label.textColor = [UIColor blackColor]; 
     label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight; 

     [tab.contentView addSubview:label]; 

     label = [[[UILabel alloc] initWithFrame:CGRectMake(180.0, 0, 150.0, tableView.rowHeight)] autorelease]; 

     [tab addColumn:340]; 

     label.tag = TAG_2; 
     label.font = [UIFont systemFontOfSize:14.0]; 
     label.text = arrayProd.artrf2; 
     label.textAlignment = UITextAlignmentLeft; 
     label.textColor = [UIColor blackColor]; 
     label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight; 

     [tab.contentView addSubview:label]; 

     label = [[[UILabel alloc] initWithFrame:CGRectMake(350.0, 0, 418.0, tableView.rowHeight)] autorelease]; 

     [tab addColumn:768]; 

     label.tag = TAG_3; 
     label.font = [UIFont systemFontOfSize:14.0]; 
     label.text = arrayProd.descri;  
     label.textAlignment = UITextAlignmentLeft; 
     label.textColor = [UIColor blackColor]; 
     label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight; 

     [tab.contentView addSubview:label]; 
    } 

    UILabel *label_1 = (UILabel *)[tab.contentView viewWithTag:TAG_1]; 
    label_1.text = arrayProd.cod; 

    UILabel *label_2 = (UILabel *)[tab.contentView viewWithTag:TAG_2]; 
    label_2.text = arrayProd.artrf2; 

    UILabel *label_3 = (UILabel *)[tab.contentView viewWithTag:TAG_3]; 
    label_3.text = arrayProd.descri; 

    return tab; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

    iMAPArrayProdutos *arrayProd = (iMAPArrayProdutos *)[iMAP objectAtIndex:indexPath.row]; 

    [iMAPProdutosPesquisar setDefaultValue:[NSString stringWithFormat:@"%@", arrayProd.cod]]; 
} 

- (IBAction)fil:(id)sender { 

    iMAPProdutosFiltro *prodFil = [[iMAPProdutosFiltro alloc] init]; 
    pop = [[UIPopoverController alloc] initWithContentViewController:prodFil]; 

    prodFil.pop = pop; 

    [prodFil release]; 

    [pop setPopoverContentSize:CGSizeMake(170, 220)]; 
    [pop presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES]; 
} 

- (void)initDatBase { 

    datBaseName = @"iMAP.sqlite"; 

    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDir = [documentPaths objectAtIndex:0]; 

    datBasePath = [documentsDir stringByAppendingPathComponent:datBaseName]; 

    [self checkAndCreateDatBase]; 
    [self readFilFromDatBase]; 

    if ([sb.text length] > 0) { 

     [self readAvancFromDatBase]; 
    } 

    [self readProdFromDatBase]; 
} 

- (void)checkAndCreateDatBase { 

    BOOL success; 

    NSFileManager *fileManager = [NSFileManager defaultManager]; 

    success = [fileManager fileExistsAtPath:datBasePath]; 

    if(success) { 

     return; 
    } 

    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:datBaseName]; 

    [fileManager copyItemAtPath:databasePathFromApp toPath:datBasePath error:nil]; 

    [fileManager release]; 
} 

- (void)readFilFromDatBase { 

    sqlite3 *datBase; 

    if(sqlite3_open([datBasePath UTF8String], &datBase) == SQLITE_OK) { 

     const char *sqlStat = "SELECT OPCAO FROM FILTRO WHERE R_E_C_N_O_ = 2"; 
     sqlite3_stmt *compiledStat; 

     if(sqlite3_prepare_v2(datBase, sqlStat, -1, &compiledStat, NULL) == SQLITE_OK) { 

      while(sqlite3_step(compiledStat) == SQLITE_ROW) { 

       opcFil = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStat, 0)]; 
      } 
     } 

     sqlite3_finalize(compiledStat); 
    } 

    sqlite3_close(datBase); 
} 

- (void)readAvancFromDatBase { 

    sqlite3 *datBase; 

    abrev = [[NSMutableArray alloc] init]; 

    if(sqlite3_open([datBasePath UTF8String], &datBase) == SQLITE_OK) { 

     const char *sqlStat; 
     sqlite3_stmt *compiledStat; 

     NSString *string1; 
     NSString *string2; 

     string1 = @"SELECT ABV_COMPLETA FROM ABREV WHERE ABV_REDUZ LIKE '%"; 
     string2 = @"%'"; 

     NSString *result = [NSString stringWithFormat:@"%@%@%@", string1, sb.text, string2]; 

     sqlStat = [result UTF8String]; 

     if(sqlite3_prepare_v2(datBase, sqlStat, -1, &compiledStat, NULL) == SQLITE_OK) { 

      while(sqlite3_step(compiledStat) == SQLITE_ROW) { 

       NSString *abvCompl = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStat, 0)]; 

       iMAPArrayAbreviatura *arrayAbrev = [[iMAPArrayAbreviatura alloc] reduz:nil completa:abvCompl observacao:nil abrUnq:nil recno:nil]; 

       [abrev addObject:arrayAbrev]; 

       [arrayAbrev release]; 
      } 
     } 

     sqlite3_finalize(compiledStat); 
    } 

    sqlite3_close(datBase); 
} 

- (void)readProdFromDatBase { 

    sqlite3 *datBase; 

    iMAP = [[NSMutableArray alloc] init]; 

    if(sqlite3_open([datBasePath UTF8String], &datBase) == SQLITE_OK) { 

     sqlite3_stmt *compiledStat; 
     const char *sqlStat; 

     if ([sb.text length] == 0) { 

      sqlStat = "SELECT COD, ARTRF2, DESCRI FROM APSB1010"; 
     } 
     else { 

      NSString *string1; 
      NSString *string2 = @"%'"; 
      NSString *result; 

      if ([opcFil isEqualToString:@"1"]) { 

       string1 = @"SELECT COD, ARTRF2, DESCRI FROM APSB1010 WHERE TRIM(COD) LIKE '%"; 

       result = [NSString stringWithFormat:@"%@%@%@", string1, sb.text, string2]; 
      } 
      else if ([opcFil isEqualToString:@"2"]) { 

       string1 = @"SELECT COD, ARTRF2, DESCRI FROM APSB1010 WHERE TRIM(ARTRF2) LIKE '%"; 

       result = [NSString stringWithFormat:@"%@%@%@", string1, sb.text, string2]; 
      } 
      else if ([opcFil isEqualToString:@"3"]) { 

       string1 = @"SELECT COD, ARTRF2, DESCRI FROM APSB1010 WHERE TRIM(DESCRI) LIKE '%"; 

       result = [NSString stringWithFormat:@"%@%@%@", string1, sb.text, string2]; 
      } 
      else if ([opcFil isEqualToString:@"4"]) { 

       string1 = @"SELECT COD, ARTRF2, DESCRI FROM APSB1010 WHERE TRIM(APLICA) LIKE '%"; 

       result = [NSString stringWithFormat:@"%@%@%@", string1, sb.text, string2]; 
      } 
      else { 

       string1 = @"SELECT COD, ARTRF2, DESCRI FROM APSB1010 WHERE ("; 
       NSString *string1 = @"SELECT * FROM APSB1010 WHERE ("; 
       NSString *string3 = @"TRIM(DESCRI) LIKE '%"; 
       NSString *string4 = @" OR "; 
       NSString *string5 = @")"; 
       cons = [[NSString alloc] init]; 

       for (int i = 0; i < [abrev count]; i++) { 

        iMAPArrayAbreviatura *arrayAbrev = (iMAPArrayAbreviatura *)[abrev objectAtIndex:i]; 

        if (i > 0) { 

         cons = [cons stringByAppendingString:string4]; 
        } 

        cons = [cons stringByAppendingString:string3]; 
        cons = [cons stringByAppendingString:arrayAbrev.completa]; 
        cons = [cons stringByAppendingString:string2]; 
       } 

       result = [NSString stringWithFormat:@"%@%@%@", string1, cons, string5]; 
      } 

      sqlStat = [result UTF8String]; 
     } 

     if(sqlite3_prepare_v2(datBase, sqlStat, -1, &compiledStat, NULL) == SQLITE_OK) { 

      while(sqlite3_step(compiledStat) == SQLITE_ROW) { 

       NSString *prodCod = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStat, 0)]; 
       NSString *prodDescri = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStat, 2)]; 
       NSString *prodArtrf2 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStat, 1)]; 

       iMAPArrayProdutos *arrayProd = [[iMAPArrayProdutos alloc] cod:prodCod prv1:nil grupo:nil picment:nil descri:prodDescri artrf2:prodArtrf2 um:nil embAp:nil desMax:nil imgAp:nil aplica:nil qAtu_01:nil qAtu_11:nil qAtu_12:nil qAtu_13:nil qAtu_14:nil prProm:nil recno:nil]; 

       [iMAP addObject: arrayProd]; 

       [arrayProd release]; 
      } 
     } 

     sqlite3_finalize(compiledStat); 
    } 

    sqlite3_close(datBase); 

    [tv reloadData]; 
} 

+ (NSString*)defaultValue { 

    return dadosProdutos; 
} 

+ (void)setDefaultValue:(NSString*)newDefaultValue { 

    if(dadosProdutos != newDefaultValue) { 

     [dadosProdutos release]; 

     dadosProdutos = [newDefaultValue retain]; 
    } 
} 

@end 

누군가 내가 뭘 잘못하고 있는지 말해 주며, 나는이 문제로 정신 나간다.

+3

[샘플 코드] (http://sscce.org/)는 문제를 재현하기에 충분하지만 간결해야합니다. 게시 된 샘플에 외부 코드가 너무 많습니다. – outis

+0

오류 코드는 무엇입니까? – Max

+0

나는 누군가 주위에 버그를 찾아서 해결할 수 있기를 바란다. 그러나 단순히 작업에 추가 할 수있는 정보를 추가 할 수 있다면 좋을 것입니다. 버그가 있다고 의심되는 코드를 강조 표시하여 시작할 수 있습니다. – Kris

답변

2

당신은 내가 datBaseName이 유지 속성으로 정의되어 있다고 가정하면

datBaseName = @"iMAP.sqlite"; 

같은 물건을 할 장소의 무리를 가지고 있지만, 여기에 그냥 그렇게 할 때, 접근을 호출하지 않고 인스턴스 변수를 설정합니다 전화 하시려면

[datBaseName release] 

계속 하시겠습니까? 나쁜 일이 발생합니다. 대신 당신은 무엇을해야

또한 다시는 접근을 호출되지 않습니다

datBasePath = [documentsDir stringByAppendingPathComponent:datBaseName]; 

같은 물건을하고있는, 그래서 datBasePath이 유지 및되지 않는이 아마도 발표 된 것이다

self.datBaseName = @"iMAP.sqlite"; 
당신이 그것을 사용하려고 할 때.

다른 문제가있을 수 있습니다. 문제를보다 쉽게 ​​발견 할 수있는 좀 더 간단한 예제로 시도해보십시오. 또한 ARC을 살펴보면 지루한 메모리 관리가 필요합니다. Xcode에는 이와 같은 문제를 추적하기위한 NSZombies과 같은 도구 모음이 있습니다.