make how array ios objective-c nsarray nsrange arrays

ios - how - declare arrays in swift



¿Cómo crear un subarreglo de NSArray usando NSRange? (3)

Como otros han señalado, está utilizando NSRange incorrecta.

Su definicion es

typedef struct _NSRange { NSUInteger location; NSUInteger length; } NSRange;

por lo tanto, el segundo parámetro de la estructura es la longitud del rango, no la ubicación del último elemento como parece pensar.

Dicho esto, lo que estás haciendo es mucho más complicado de lo que debería ser.

¿Cuál es el propósito de producir un subarreglo de una longitud conocida y luego devolver la longitud del propio subarreglo? Teniendo esto en cuenta:

return [[array subarrayWithRange:NSMakeRange(3, 8)] count];

debe ser (usando NSRange correctamente)

return [[array subarrayWithRange:NSMakeRange(3, 6)] count];

pero en realidad puede ser solo

return 6;

o si la longitud del rango es un parámetro

return length;

Nuevamente, no hay necesidad en el mundo de cortar una matriz y contar. La longitud es conocida a priori.

Así que en el contexto de UITableViewDataSource , tienes que

  • devuelva el recuento para cada sección en -tableView:numberOfRowsInSection: Algo como

    switch(section) { case 0: return 2; case 1: return 18; }

  • devuelve los objetos reales en tableView:cellForRowAtIndexPath: Algo como

    id object = nil; switch (indexPath.section) { case 0: object = self.objects[indexPath.row]; break; case 1: object = self.objects[2 + indexPath.row]; break; } ...

Como consejo adicional, recomendaría el uso de una notación diferente para las estructuras de construcción.

NSMakeRange(0, 42)

puede ser escrito

(NSRange){ .location = 0, .length = 42 }

que es mucho más legible (y menos propenso a errores, especialmente cuando tiene dudas sobre el significado de los parámetros).

Incluso

(NSRange){ 0, 42 }

es aceptable. Creo que es mejor (y más corto) que NSMakeRange , pero pierde los beneficios o la legibilidad.

Tengo un Array con contenido. Como es habitual, contiene 20 objetos. Quiero que la misma matriz se divida en 2 secciones en Tableview. Estoy tratando de implementarlo con NSMake en la matriz actual. Por ejemplo, necesito entrar en la primera tabla de TableView 3 filas y la segunda contendrá todo el resto (17 filas).

switch (section) { case 0: return [[array subarrayWithRange:NSMakeRange(3, 8)] count]; // in this line, it always takes from the first object in array, despite I told hime start from 3 (If I understand right, how to works NSMakeRange) break; case 1: return [[array subarrayWithRange:NSMakeRange(9, 19)] count]; // here my app is crashing with an error //*** Terminating app due to uncaught exception ''NSRangeException'', reason: ''*** -[NSArray subarrayWithRange:]: range {9, 19} extends beyond bounds [0 .. 19]'' default: break; }

¿Alguien me puede ayudar con eso?


Ok he resuelto mi problema

En mi clase de Fetcher lo hice

_sectionOne = [news objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 3)]]; _sectionTwo = [news objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(3, 17)]];

entonces

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 2; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { switch (section) { case 0: return [_sectionOne count]; break; case 1: return [_sectionTwo count]; break; default: break; } return 0; }

luego en el método cellForRowAtIndexPath:

switch (indexPath.section) { case 0: item = [_sectionOne objectAtIndex:indexPath.row]; break; case 1: item = [_sectionTwo objectAtIndex:indexPath.row]; break; default: break; }

item - es mi NSObject con MVC

Así que está trabajando como yo quería :)

Gracias por tratar de ayudarme.

Aclamaciones


NSMakeRange se define como (startingIndex, length) NSMakeRange (startingIndex, length) , no (start, end) que parece ser cómo intentas usarlo.

Entonces, si necesitas los primeros 3 objetos, el resto se vería así:

switch (section) { case 0: // This returns objects 0-2 in the array return [array subarrayWithRange:NSMakeRange(0, 3)]; case 1: // This returns objects 3-20 in the array return [array subarrayWithRange:NSMakeRange(3, 17)]; default: break; }

Editar: De acuerdo con su comentario, en realidad está buscando el recuento para regresar en el número de filas en la sección. Dado que está utilizando un número fijo de filas, puede devolver el número real dentro de la declaración del caso.

switch (section) { case 0: // This returns the count for objects 0-2 in the array return 3; case 1: // This returns the count for objects 3-20 in the array return 17; default: break; }

En realidad, no es necesario utilizar [subarrayWithRange] , ni NSMakeRange . Si en algún momento necesita hacer referencia a la matriz real, obtendrá un objeto NSIndexPath que puede usar para obtener el objeto de su matriz. Deberá usar las propiedades de sección y fila.

Edición: NSRange -> NSMakeRange