Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i have the code below that iterate on every book on my bookObjects array, my problem is addObject is inserting/adding my aBook object on random index instead of adding it at the end of self.books

i just want it to follow the order of the books in bookObjects, no specific order or sorting.

books is an NSMutableArray

NSArray *bookObjects = [element childrenNamed:@"books"];

int i = 0;
for(SMXMLElement *child in bookObjects)
{
    NSString *isbn = [child valueWithPath:@"isbn"]; 
    NVBook *aBook = [self getBookByISBN:isbn];
    if(nil == aBook)
    {
        aBook = [NVBook insertBookInContext:[self managedObjectContext]];
        aBook.isbn = isbn;

        [self.books addObject:aBook];
    }

    aBook.indexInList = i++;
    [aBook updateContentWithElement:child];
}

additional code

+ (NVBook *)insertBookInContext:(NSManagedObjectContext*)context
{
    return [NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:context];
}


- (NVBook *)getBookByISBN:(NSString *)aISBN
{
    NVBook *aBook = nil;

    for(NVBook *book in self.books)
    {
        if([book.isbn isEqual:aISBN])
        {
            aBook = book;
            break;
        }
    }

    return aBook;
}
share|improve this question
2  
addObject: is defined to add at the end of the array. I would suggest adding a NSLog(@"%@", aBook); inside your loop to verify that it is called in the order you expect. –  James Sep 24 '12 at 2:26
1  
addObject will add the book to the end of the array, something else must be changing the order. I'm guessing that something is changing bookObjects rather than books. –  rdelmar Sep 24 '12 at 2:27
    
@rdelmar bookObjects is consistent, it has the same order everytime i load it, at the end of loop whenever i do a "po self.books" on my debugger, the order are all messed up. my bookObjects from XML are all correct. –  Jemer B Garibay Sep 24 '12 at 2:32
    
@James i do "po aBook" on debugger on each item on the loop and its in correct order –  Jemer B Garibay Sep 24 '12 at 2:33
    
What does insertBookInContext: do? It's hard to tell what's going on without knowing what some of your methods do. –  rdelmar Sep 24 '12 at 2:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.