2009-10-03 22 views
5

Tengo esta gran tabla que funciona sin errores, incluso si me parece demasiado lento en comparación con las celdas más complejas que abrí de ejemplos descargados. El problema viene cuando hago clic en una celda, y luego regresó, en pocos segundos de desplazamiento rápido de la aplicación se bloquea en la línea de: charImage.image = [self imageForIndex:ch.charId];¿por qué mi aplicación se bloquea? UITable y controladores

si elimino que está fallando en la siguiente línea: titleLabel.text = ch.title;

Hay alguien familiarizado con esto? Gracias.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
//NSLog(@"add a new cell at index path %@", indexPath); 
// Each subview in the cell will be identified by a unique tag. 
static NSUInteger const kTitleLabelTag = 2; 
static NSUInteger const kCharImageTag = 3; 
static NSString *kCellID = @"CellID"; 

// Configure the cell 


// Declare references to the subviews which will display the char data. 
UILabel *titleLabel = nil; 
UIImageView *charImage = nil; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID]; 

if (cell == nil) { 
    // No reusable cell was available, so we create a new cell and configure its subviews. 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID] autorelease]; 
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
    [cell setBackgroundColor:[UIColor clearColor]]; 
    // 
    charImage = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"glyphs/a/1.png"]] autorelease]; 
    charImage.tag = kCharImageTag; 
    charImage.autoresizingMask = UIViewAutoresizingNone; 
    [cell.contentView addSubview:charImage]; 

    titleLabel = [[[UILabel alloc] initWithFrame:CGRectMake(60, 10, 215, 20)] autorelease]; 
    titleLabel.tag = kTitleLabelTag; 
    titleLabel.font = [UIFont systemFontOfSize:16]; 
    titleLabel.textColor = [UIColor whiteColor]; 
    titleLabel.backgroundColor = [UIColor clearColor]; 
    titleLabel.adjustsFontSizeToFitWidth = YES; 
    [cell.contentView addSubview:titleLabel]; 

} else { 
    // A reusable cell was available, so we just need to get a reference to the subviews using their tags. 
    charImage = (UIImageView *)[cell.contentView viewWithTag:kCharImageTag]; 
    titleLabel = (UILabel *)[cell.contentView viewWithTag:kTitleLabelTag]; 
} 


// Get the specific info for this row. 
NSUInteger section = [indexPath section]; 
NSUInteger row = [indexPath row]; 
Char *ch = (Char *)[charsList objectAtIndex:row+section*26]; 

// Set the relevant data for each subview in the cell. 
// Set the image in the cell 
charImage.image = [self imageForIndex:ch.charId]; 
[charImage sizeToFit]; 

int centerX = 30; 
int centerY = 23; 
CGSize size = charImage.frame.size; 
charImage.frame = CGRectMake((int)(centerX - size.width/2), 
          (int)(centerY - size.height/2), 
          size.width, size.height); 

titleLabel.text = ch.title; 

return cell; 

}

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

InstantInsightAppDelegate *delegate = [[UIApplication sharedApplication] delegate]; 
NSUInteger section = [indexPath section]; 
NSUInteger row = [indexPath row]; 
Char *ch = (Char *)[charsList objectAtIndex:row+26*section]; 

SqlQueries *db = [SqlQueries alloc]; 
NSArray *glyphsList = [db readGlyphsFromDatabaseAtId: ch.charId]; 
NSArray *charDescription = [db readMoreInfoFromDatabaseAtId: ch.charId]; 
Char *charDetails = [db readInstructionsAndQuotesFromDatabaseAtId: ch.charId]; 
[db release]; 
[ch release]; 

// Navigation logic -- create and push a new view controller 
self.glyphsView = [[GlyphsViewController alloc] initWithStyle:UITableViewStyleGrouped]; 

self.glyphsView.glyphsList = glyphsList; 
self.glyphsView.charDetails = charDetails; 
self.glyphsView.charDescription = charDescription; 
[delegate.navController pushViewController:self.glyphsView animated:YES]; 
[self.glyphsView release]; 
self.glyphsView = nil; 

}


Aquí hay un error detallado: no dice nada, pero estoy seguro de que he visto algo con una excepción

[La sesión comenzó en 2009-10-05 07:41:25 +0300.] GNU gdb 6.3.50-20050815 (Versión de Apple gdb-967) (Mar. Jul 14 02:11:58 UTC 2009) Copyright 2004 Free Software Foundation, Inc. GDB es software libre, cubierto por la Licencia Pública General de GNU, y usted es invitamos a cambiarlo y/o distribuir copias de él bajo ciertas condiciones Escribe "mostrar copia" para ver las condiciones. No hay absolutamente ninguna garantía para GDB. Escriba "mostrar garantía" para más detalles. Este GDB se ha configurado como "i386-manzana-Darwin" .sharedlibrary aplicar reglas de carga-todo Colocación de procesar 96464. (BGF)^C donde

#0 0x95fd5688 in objc_msgSend() 
#1 0x00002f60 in -[IndexViewController tableView:cellForRowAtIndexPath:] (self=0xd19610, _cmd=0x319a6b9c, tableView=0x101be00, indexPath=0xd2e890) at /Users/Cristi/Documents/xcode - iPhone/Instant Insight/InstantInsight/Classes/IndexViewController.m:115 
#2 0x30944bd0 in -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:]() 
#3 0x3093e1fc in -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:]() 
#4 0x309501f1 in -[UITableView(_UITableViewPrivate) _updateVisibleCellsNow]() 
#5 0x30947715 in -[UITableView layoutSubviews]() 
#6 0x00b3dd94 in -[CALayer layoutSublayers]() 
#7 0x00b3db55 in CALayerLayoutIfNeeded() 
#8 0x00b3d3ae in CA::Context::commit_transaction() 
#9 0x00b3d022 in CA::Transaction::commit() 
#10 0x00b452e0 in CA::Transaction::observer_callback() 
#11 0x30245c32 in __CFRunLoopDoObservers() 
#12 0x3024503f in CFRunLoopRunSpecific() 
#13 0x30244628 in CFRunLoopRunInMode() 
#14 0x32044c31 in GSEventRunModal() 
#15 0x32044cf6 in GSEventRun() 
#16 0x309021ee in UIApplicationMain() 
#17 0x00002718 in main (argc=1, argv=0xbfffee50) at /Users/Cristi/Documents/xcode - iPhone/Instant Insight/InstantInsight/main.m:14 
+0

Char * ch = (Char *) [charsList objectAtIndex: fila + sección * 26]; me parece muy extraño ¿Qué tipo de objetos pones en charsList? – diederikh

+0

Estoy colocando objetos Char. Char contiene solo pocas NSStrings que se completan desde la base de datos. Si simplemente NSLog estos valores, están bien, incluso en el momento se bloquea. –

Respuesta

5

¿Qué tipo de "estrellarse"? ¿EXC_BAD_ACCESS (desreferenciando un puntero que no apunta a una ubicación válida)? O un objc_exception_throw de algún tipo?

Suponiendo que significa un EXC_BAD_ACCESS ...

Esto sería debido a que el valor de la "ch" de regresar de [charsList objectAtIndex:row+section*26] no es un objeto válido.

La razón exacta de esto debe descubrirse a sí mismo, pero la causa más probable es que haya lanzado el objeto demasiadas veces. También existe la posibilidad de que el objeto no fuera un objeto Objective-C válido cuando se insertó en NSArray.

A veces ayuda configurar NSZombieEnabled (comando-opción-x, vaya a la pestaña Argumentos y agregue name = NSZombieEnabled y value = 1 a las variables de entorno) ya que esto arrojará una excepción inmediatamente si intenta utilizar un objeto desasignado objeto.

-

Sin relación estilística punto: usted está asignando SqlQueries pero no inicializarlo. Si alloc, siempre, siempre init. es decir, [[SqlQueries alloc] init]. Si no te importa init porque no tienes variables de instancia, entonces no deberías tener un alloc de todos modos, tus métodos deberían ser métodos de clase en su lugar.

+0

Gracias por las explicaciones detalladas. Creo que puedo poner algo en el init de los SqlQueries. Ahora, estoy seguro de que mi error es ese con la excepción, porque allí es donde tengo la idea de poner un try catch, y lamentablemente todavía se cuelga, no se llama al nslog del catch. No estoy seguro de qué más decir sobre mi código. –

+0

No puede capturar un EXC_BAD_ACCESS. Necesita averiguar por qué sus objetos en la charList no son válidos. Use puntos de interrupción en el depurador o NSLog en toda la lista de trabajo de forma regular para ver cuándo va mal (NSLog bloqueará el programa una vez que el objeto charList deje de ser válido). Lo más probable es que tenga un código en alguna parte que libere (o libere) uno de los objetos Char cuando nunca lo haya alojado o retenido; esto hace que el objeto Char se invalide aunque todavía lo necesite el charList formación. –

+0

Así que sí, miré con más atención para ver si estoy desmantelando el objeto Char de la matriz como dijiste, y lo estaba haciendo. La respuesta es eliminar esta línea: [ch release]; Gracias de nuevo. –

Cuestiones relacionadas