Search code examples
javascriptjsoncappuccino

CPRangeException thrown when objects added to an CPArray


In my cappuccino app, I am reading from an RoR backend via JSON and putting the results onto a list. When the app first loads everything is fine, but when I edit an item (and write the edit to the database) there is an error generated when the items list is refreshed.

The error is CPRangeException: -[_CPJavaScriptArray objectAtIndex:]: index (-1) beyond bounds (3).

I get this error even if I edit an item without making any actual changes. The JSON string received by the app remains exactly the same in this case, there are no items added or removed and therefore the array should not be written to out of bounds.

Here is my code:

- (void)connection:(CPRURLConnection)connection didReceiveData:(CPString)data
{
    if(connection === listConnection)
    {        
        var results = JSON.parse(data) ;
        var posts = [Post initFromJSONObjects:results];
        [postListView setContent:posts] ;
        // My error occurs at the above line
        [postListView setSelectionIndexes:[[CPIndexSet alloc] initWithIndex:0]] ;
    }
 }

I am not sure if it's an error with my code or if it's some kind of inconsistency with the cappuccino framework. Does anybody know what I can do to fix this?

The rest of the code can be found here


Solution

  • You should probably simply log what's in posts before setting it. CPLog.info('posts: ' + posts); should work, or console.log(posts). Next you can set a 'break on uncaught exception' debug point in Chrome or Safari to stop at the actual error you are seeing. Make sure you run your app using index-debug.html so that you get full method names. Then it should be an easy matter to look at the calling stack to see where things are going wrong. There's a lot of information on debugging a Cappuccino app here.