Error de aserción en dequeueReusableCellWithIdentifier: forIndexPath:


Así que estaba haciendo un lector de rss para mi escuela y terminé el código. Hice la prueba y me dio ese error. Aquí está el código al que se refiere:

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

        cell = 
         [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle  
                                reuseIdentifier:CellIdentifier];

    }

Aquí está el error en la salida:

2012-10-04 20:13:05.356 Reader [4390: c07] * Fallo de aserción en -[UITableView dequeueReusableCellWithIdentifier: forIndexPath:], / SourceCache/UIKit_Sim/UIKit-2372 / UITableView.h: 4460 2012-10-04 20: 13: 05.357 Lector [4390: c07] * Aplicación de terminación debido a no capturada excepción 'NSInternalInconsistencyException', motivo: 'no se puede dequeue una celda con identificador de celda - debe registrar un nib o una clase para el identificador o conectar una celda prototipo en un guion gráfico' * Pila de la primera llamada del tiro: (0x1c91012 0x10cee7e 0x1c90e78 0xb64f35 0xc7d14 0x39ff 0xd0f4b 0xd101f 0xb980b 0xca19b 0x6692d 0x10e26b0 0x228dfc0 0x228233c 0x228deaf 0x1058cd 0x4e1a6 0x4ccbf 0x4cbd9 0x4be34 0x4bc6e 0x4ca29 0x4f922 0xf9fec 0x46bc4 0x47311 0x2cf3 0x137b7 0x13da7 0x14fab 0x26315 0x2724b 0x18cf8 0x1becdf9 0x1becad0 0x1c06bf5 0x1c06962 0x1c37bb6 0x1c36f44 0x1c36e1b 0x147da 0x1665c 0x2a02 0x2935) libc++abi.dylib: terminate llama lanzar una excepción

Y aquí está el código que muestra en la pantalla de error:

int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

Por favor ayuda!

Author: Erik Godard, 2012-10-05

20 answers

Estás usando el método dequeueReusableCellWithIdentifier:forIndexPath:. La documentación para ese método dice esto:

Importante: Debe registrar una clase o archivo nib usando el método registerNib:forCellReuseIdentifier: o registerClass:forCellReuseIdentifier: antes de llamar a este método.

No ha registrado un nib o una clase para el identificador de reutilización "Cell".

Mirando su código, parece esperar que el método dequeue devuelva nil si no tiene una celda para darle. Necesitas usar dequeueReusableCellWithIdentifier: para eso comportamiento:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

Observe que dequeueReusableCellWithIdentifier: y dequeueReusableCellWithIdentifier:forIndexPath: son métodos diferentes. Véase el documento para el primero y el segundo.

Si quieres entender por qué querrías usar alguna vez dequeueReusableCellWithIdentifier:forIndexPath:, echa un vistazo a este Q&A .

 479
Author: rob mayoff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:19

Creo que este error se trata de registrar su nib o clase para el identificador.

Para que pueda mantener lo que está haciendo en su función tableView: cellForRowAtIndexPath y simplemente agregue el código a continuación en su viewDidLoad:

[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];

Ha funcionado para mí. Espero que pueda ayudar.

 137
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-13 09:42:13

Aunque esta pregunta es bastante antigua, hay otra posibilidad: Si está utilizando guiones gráficos, simplemente tiene que configurar el CellIdentifier en el guion gráfico.

Así que si su CellIdentifier es "Cell", simplemente establezca la propiedad" Identifier": introduzca la descripción de la imagen aquí

Asegúrate de limpiar tu constitución después de hacerlo. XCode a veces tiene algunos problemas con las actualizaciones de Storyboard

 66
Author: Sebastian Borggrewe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-18 15:36:17

Tuve el mismo problema reemplazando con

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

   if (cell==nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

    }

Resuelto

 59
Author: iMeMyself,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-26 06:24:31

El problema es muy probable porque config custom UITableViewCell en storyboard pero no usa storyboard para crear instancias de su UITableViewController que usa este UITableViewCell. Por ejemplo, en MainStoryboard, tiene una subclase UITableViewController llamada MyTableViewController y tiene una dinámica personalizada UITableViewCell llamada MyTableViewCell con el identificador id "myCell".

Si crea su personalizado UITableViewController así:

 MyTableViewController *myTableViewController = [[MyTableViewController alloc] init];

No registrará automáticamente su tableviewcell personalizado para usted. Tienes que registrarte manualmente se.

Pero si usas storyboard para crear instancias MyTableViewController, así:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
MyTableViewController *myTableViewController = [storyboard  instantiateViewControllerWithIdentifier:@"MyTableViewController"];

¡Sucede algo bueno! UITableViewController registrará automáticamente su celda de vista de tabla personalizada que defina en storyboard para usted.

En su método delegado "cellForRowAtIndexPath", puede crear su celda de vista de tabla de la siguiente manera:

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

//Configure your cell here ...

return cell;
}

DequeueReusableCellWithIdentifier creará automáticamente una nueva celda para usted si no hay una celda reutilizable disponible en el reciclaje cola.

¡Entonces has terminado!

 25
Author: James Wang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-04 13:48:22

Simplemente agregaré que Xcode 4.5 incluye el nuevo dequeueReusableCellWithIdentifier:forIndexPath:
en su código de plantilla por defecto - un potencial gotcha para los desarrolladores que esperan el antiguo método dequeueReusableCellWithIdentifier:.

 19
Author: Brian Shriver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-29 19:31:48

En su storyboard debe establecer el 'Identificador' de su celda prototipo para que sea el mismo que su CellReuseIdentifier "Cell". Entonces no recibirá ese mensaje o necesitará llamar a esa función registerClass:.

 18
Author: Steven,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-03 23:43:44

Solución Swift 2.0:

Necesita entrar en su Inspector de atributos y agregar un nombre para su Identificador de celdas:

introduzca la descripción de la imagen aquí

Entonces necesitas hacer que tu identificador coincida con tu dequeue de esta manera:

let cell2 = tableView.dequeueReusableCellWithIdentifier("ButtonCell", forIndexPath: indexPath) as! ButtonCell

Alternativamente

Si estás trabajando con un plumín es posible que necesites registrar tu clase en tu cellForRowAtIndexPath:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {       

    tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "SwitchCell")

    // included for context            
    let cell = tableView.dequeueReusableCellWithIdentifier("SwitchCell", forIndexPath:indexPath) as! SwitchCell

    //... continue    
}

La referencia de clase UITableView de Apples dice:

Antes de dequeueing cualquier celda, llame a este método o el registerNib: forCellReuseIdentifier: método para indicar la tabla para crear nuevas celdas. Si una celda del tipo especificado no está actualmente en una cola de reutilización, la vista de tabla utiliza la información proporcionada para cree un nuevo objeto de celda automáticamente.

Si ha registrado previamente una clase o un archivo nib con la misma reutilización identificador, la clase que especifique en el parámetro cellClass reemplaza la vieja entrada. Usted puede especificar nil para cellClass si quieres anule el registro de la clase del identificador de reutilización especificado.

Aquí está el código de Apple Swift 2.0 framework:

// Beginning in iOS 6, clients can register a nib or class for each cell.
// If all reuse identifiers are registered, use the newer -dequeueReusableCellWithIdentifier:forIndexPath: to guarantee that a cell instance is returned.
// Instances returned from the new dequeue method will also be properly sized when they are returned.

@available(iOS 5.0, *)
func registerNib(nib: UINib?, forCellReuseIdentifier identifier: String)

@available(iOS 6.0, *)
func registerClass(cellClass: AnyClass?, forCellReuseIdentifier identifier: String)
 17
Author: Dan Beaulieu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-21 01:08:21

Si va con Celdas estáticas personalizadas {[3] } simplemente comente este método:

//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    static NSString *CellIdentifier = @"notificationCell";
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//    return cell;
//}

Y dar a las celdas un identificador en "Inspector de atributos" en storyboard.

 3
Author: Francisco Gutiérrez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-05 04:52:06

Les doy la respuesta tanto en Objective C como en Swift.Antes de eso quiero decir

Si usamos el dequeueReusableCellWithIdentifier:forIndexPath:, debemos registrar una clase o archivo nib usando el método registerNib: forCellReuseIdentifier:o registerClass: forCellReuseIdentifier: antes de llamar a este método como La documentación de Apple Dice

Así que añadimos registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier:

Una vez que registramos una clase para el identificador especificado y se debe crear una nueva celda, este método inicializa celda llamando a su método initWithStyle:reuseIdentifier:. Para celdas basadas en nib, este método carga el objeto cell desde el archivo nib proporcionado. Si una celda existente estaba disponible para su reutilización, este método llama al método prepareForReuse de la celda en su lugar.

En el método viewDidLoad debemos registrar la celda

Objetivo C

OPCIÓN 1:

[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];

OPCIÓN 2:

[self.tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:@"cell"];

En el código anterior nibWithNibName:@"CustomCell" dar el nombre de su plumín en lugar de mi nombre del plumín CustomCell

SWIFT

OPCIÓN 1:

tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

OPCIÓN 2:

tableView.registerNib(UINib(nibName: "NameInput", bundle: nil), forCellReuseIdentifier: "Cell") 

En el código anterior nibName:"NameInput" da el nombre de tu plumín

 3
Author: user3182143,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-23 06:34:26

Pasé horas anoche trabajando en por qué mi tabla generada programáticamente se bloqueaba en [MyTable setDataSource: self]; Estaba bien comentar y aparecer una tabla vacía, pero se bloqueaba cada vez que intentaba llegar a la fuente de datos;

Tenía la delegación configurada en el archivo h: @interfaz MyViewController: UIViewController

Tenía el código fuente de datos en mi implementación y todavía BOOM!, chocar cada vez! GRACIAS a " xxd " (nr 9): agregar esa línea de código lo resolvió para mí! De hecho, estoy lanzando una tabla desde un botón IBAction, así que aquí está mi código completo:

    - (IBAction)tapButton:(id)sender {

    UIViewController* popoverContent = [[UIViewController alloc]init];

    UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 300)];
    popoverView.backgroundColor = [UIColor greenColor];
    popoverContent.view = popoverView;

    //Add the table
    UITableView *table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 200, 300)         style:UITableViewStylePlain];

   // NEXT THE LINE THAT SAVED MY SANITY Without it the program built OK, but crashed when      tapping the button!

    [table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    table.delegate=self;
    [table setDataSource:self];
    [popoverView addSubview:table];
    popoverContent.contentSizeForViewInPopover =
    CGSizeMake(200, 300);

    //create a popover controller
    popoverController3 = [[UIPopoverController alloc]
                          initWithContentViewController:popoverContent];
    CGRect popRect = CGRectMake(self.tapButton.frame.origin.x,
                                self.tapButton.frame.origin.y,
                                self.tapButton.frame.size.width,
                                self.tapButton.frame.size.height);


    [popoverController3 presentPopoverFromRect:popRect inView:self.view   permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];



   }


   #Table view data source in same m file

   - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
   {
    NSLog(@"Sections in table");
    // Return the number of sections.
    return 1;
   }

   - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
  {
    NSLog(@"Rows in table");

    // Return the number of rows in the section.
    return myArray.count;
   }

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

    NSString *myValue;

    //This is just some test array I created:
    myValue=[myArray objectAtIndex:indexPath.row];

    cell.textLabel.text=myValue;
    UIFont *myFont = [ UIFont fontWithName: @"Arial" size: 12.0 ];
    cell.textLabel.font  = myFont;

    return cell;
   }

Por cierto: el botón debe estar vinculado como IBAction y como IBOutlet si desea anclar la ventana emergente a él.

UIPopoverController * Popovercontroller 3 se declara en el archivo H directamente después de @interfaz entre {}

 2
Author: Simone,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-17 09:54:23

FWIW, obtuve este mismo error cuando olvidé establecer el identificador de celda en el guion gráfico. Si este es su problema, en el guion gráfico, haga clic en la celda de vista de tabla y establezca el identificador de celda en el editor de atributos. Asegúrese de que el identificador de celda que establece aquí es el mismo que

static NSString *CellIdentifier = @"YourCellIdenifier";
 2
Author: honkskillet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-14 05:26:07

Tuve el mismo problema, estaba teniendo el mismo error y para mí funcionó así:

[self.tableView registerNib:[UINib nibWithNibName:CELL_NIB_HERE bundle: nil] forCellReuseIdentifier:CELL_IDENTIFIER_HERE];

Tal vez sea útil para alguien más.

 2
Author: CarmenA,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-24 11:22:00

Configuré todo correctamente en el guion gráfico e hice una compilación limpia, pero seguí recibiendo el error " debo registrar un plumín o una clase para el identificador o conectar una celda prototipo en un guion gráfico "

[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];

Corregido el error, pero todavía estoy en una pérdida. No estoy usando una 'celda personalizada', solo una vista con una vista de tabla incrustada. He declarado el viewcontroller como delegado y fuente de datos y me he asegurado de que el identificador de celda coincida con el archivo. ¿qué está pasando aquí?

 2
Author: FrostyL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-29 19:17:02

Trabajando con Swift 3.0:

override func viewDidLoad() {
super.viewDidLoad()

self.myList.register(UINib(nibName: "MyTableViewCell", bundle: nil), forCellReuseIdentifier: "Cell")
}



public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = myList.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath) as! MyTableViewCell

return cell
}
 2
Author: norbDEV,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-26 18:44:32

Esto puede parecer estúpido para algunas personas, pero me atrapó. Estaba recibiendo este error y el problema para mí era que estaba tratando de usar celdas estáticas pero luego agregar dinámicamente más cosas. Si está llamando a este método, sus celdas deben ser prototipos dinámicos. Seleccione la celda en storyboard y bajo el inspector de atributos, lo primero que dice 'Contenido' y debe seleccionar prototipos dinámicos no estáticos.

 1
Author: Chase Roberts,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-16 18:12:47

Solo un suplemento de las respuestas: Puede haber un momento en el que establezcas todas las cosas bien, pero accidentalmente puedes agregar otras UIs en ti .xib, como una UIButton:introduzca la descripción de la imagen aquí Simplemente elimine la interfaz de usuario adicional, funciona.

 1
Author: DrustZ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-25 15:00:07

Asegúrese de que el identificador CellIdentifier == de la celda en un guion gráfico, ambos nombres son los mismos. Espero que esto funcione para u

 1
Author: Ankit garg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-17 09:49:01

En mi caso, el accidente ocurrió cuando llamé deselectRowAtIndexPath:

La línea era [tableView deselectRowAtIndexPath:indexPath animated:YES];

Cambiándolo a [self.tableView deselectRowAtIndexPath:indexPath animated:YES]; ¡ARREGLÉ MI PROBLEMA!

Espero que esto ayude a alguien

 0
Author: Offek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-02 22:34:29

En Swift este problema se puede resolver añadiendo el siguiente código en su

ViewDidLoad

Método.

tableView.registerClass(UITableViewCell.classForKeyedArchiver(), forCellReuseIdentifier: "your_reuse_identifier")
 0
Author: arango_86,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-19 05:37:02