我有下面的代码迭代我的bookObjects数组上的每本书,我的问题是addObject是在随机索引上插入/添加我的aBook对象而不是在self.books结束时添加它。
我只是希望它遵循bookObjects中书籍的顺序,没有特定的顺序或排序。
books是一个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];
}
附加代码
+ (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;
}