2012-06-29 19 views
15

Este es mi problema: tengo esta pequeña UITableView en mi guión gráfico: enter image description hereConjunto UITableView Delegado y el origen de datos

y este es mi código:

SmallTableViewController.h

#import <UIKit/UIKit.h> 
#import "SmallTable.h" 

@interface SmallViewController : UIViewController 

@property (weak, nonatomic) IBOutlet UITableView *myTable; 

@end 

SmallTableViewController.m

#import "SmallViewController.h" 

@interface SmallViewController() 

@end 

@implementation SmallViewController 
@synthesize myTable = _myTable; 

- (void)viewDidLoad 
{ 
    SmallTable *myTableDelegate = [[SmallTable alloc] init]; 
    [super viewDidLoad]; 
    [self.myTable setDelegate:myTableDelegate]; 
    [self.myTable setDataSource:myTableDelegate]; 

    // Do any additional setup after loading the view, typically from a nib. 
} 

- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
} 

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

@end 

Ahora, como puede ver, quiero establecer una instancia llamada myTableDelegate como Delegate y DataSource de myTable.

Esta es la fuente de la clase SmallTable.

SmallTable.h

#import <Foundation/Foundation.h> 

@interface SmallTable : NSObject <UITableViewDelegate , UITableViewDataSource> 

@end 

SmallTable.m

@implementation SmallTable 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 
    return 0; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    // Return the number of rows in the section. 
    return 5; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    // Configure the cell... 
    cell.textLabel.text = @"Hello there!"; 

    return cell; 
} 

#pragma mark - Table view delegate 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSLog(@"Row pressed!!"); 
} 

@end 

que implementa el método de todo UITableViewDelegate y UITableViewDataSource que la necesidad de aplicación. ¿Por qué simplemente se bloquea antes de que aparezca la vista?

Gracias!

+0

Podría pegar el error? – JonLOo

+0

¿Se pueden agregar registros de bloqueo también? – rishi

+0

Revise la discusión en el hilo - http://stackoverflow.com/questions/254354/uitableview-issue-when-section-separate-delegate-datasource – rishi

Respuesta

15

rickster tiene razón. Pero supongo que necesita usar un calificador strong para su propiedad ya que al final de su método viewDidLoad el objeto será desasignado de todos modos.

@property (strong,nonatomic) SmallTable *delegate; 

// inside viewDidload 

[super viewDidLoad]; 
self.delegate = [[SmallTable alloc] init];  
[self.myTable setDelegate:myTableDelegate]; 
[self.myTable setDataSource:myTableDelegate]; 

¿Pero hay alguna razón para usar un objeto separado (fuente de datos y delegado) para su tabla? ¿Por qué no configura SmallViewController como el origen y el delegado para su tabla?

Además, no está creando la celda de la manera correcta. Estas líneas no hacen nada:

static NSString *CellIdentifier = @"Cell"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

// Configure the cell... 
cell.textLabel.text = @"Hello there!"; 

dequeueReusableCellWithIdentifier recupera simplemente a partir de la tabla "caché" una célula que ya se ha creado y que pueden ser reutilizados (esto para evitar el consumo de memoria) pero no se ha creado ninguna.

¿Dónde estás alloc-init?Hacer esto en su lugar:

static NSString *CellIdentifier = @"Cell"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if(!cell) { 
    cell = // alloc-init here 
} 
// Configure the cell... 
cell.textLabel.text = @"Hello there!"; 

dicen Además de numberOfSectionsInTableView volver 1 en lugar de 0:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 
    return 1; 
} 
4

¿Presumiblemente usted está usando ARC? Su myTableDelegate solo se referencia en una variable local en viewDidLoad; una vez que el método finaliza, se desasigna. (En el patrón de delegado/origen de datos, los objetos no son propietarios de sus delegados, por lo que las referencias de la vista de tabla a su objeto son débiles.) No esperaría que eso solo cause un bloqueo, pero es probable que sea la clave de su problema.

+0

OK, acabo de crear un nuevo delegado @property (débil, no atómico) de SmallTable *; Ahora la aplicación no falla, pero ... ¡la vista de tabla está vacía! No puedo entender por qué... –

1

setDelegate no retendrá el delegado.

Y

numberOfSectionsInTableView método tiene que volver 1 en lugar de 0;

0

El delegado de un objeto UITableView debe adoptar el protocolo UITableViewDelegate. Los métodos opcionales del protocolo permiten al delegado administrar selecciones, configurar encabezados de secciones y pies de página, ayuda a eliminar métodos.

enter image description here

1
(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 
    return 0; 
} 

Número de secciones se debe establecer al menos un

Cuestiones relacionadas