Obtener errores al usar plist en NSMutableArray

So I am using a plist file to store a NSMutableArray and when added an object also save it to that plist file. But I am getting this error:

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'


NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:1];
_prsPath = [documentsDirectory stringByAppendingPathComponent:@"records.plist"];

prs = [[NSMutableArray alloc] initWithContentsOfFile:_prsPath];

if (prs == nil) {
    prs = [NSMutableArray array];

and after "addObject":

[prs writeToFile:_prsPath atomically:YES];

Struggeling with this code for hours.

Gracias de antemano!

preguntado el 26 de agosto de 12 a las 13:08

First, check if paths is nil, before trying to access any of its elements. Then, when trying to access its elements, check if the array contains enough elements (more than 0). Actually, you may skip step one as that will return 0 even if that array is nil. -

1 Respuestas

¿No debería ser eso? NSString *documentsDirectory = [paths objectAtIndex:0];?

The error you're getting is an out-of-bounds error. It means you're asking an array for an object at an index that is above it's highest index. In this case you're asking for an object at index 1 (2nd object) even though the highest index is 0 (only one object in the array).

Respondido 26 ago 12, 13:08

Uh, changed 1 to 0 getting this error: Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array' - sjors

Btw, if array is likely to contain only one item, I prefer to use [ar lastObject] since it will silently return nil if there's no items at all. - pronvit

it's going to contain as much items as the user adds. - sjors

On which line do you get the error? I don't see any other ``objectForIndex:` calls other then that. - BateristaB

uhh there are. This is the code I am using to add objects. pastie.org/private/byxjmf5k6rpsfcj4uz8qcw - sjors

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.