I understand what the EXC_BAD_ACCESS error EXC_BAD_ACCESS in general, but I am puzzled by what happens in my case.
I have my own class that has the NSComparator property sortWithThisComparator . If this property is set by the user when I insert the element into the properties array of the items instance class, I use a comparator to determine the location of the insert:
- (void) insertItem:(id<NSCoding, CKArchivingItem>) item { if (arrayObjectClassString && ![item isKindOfClass:NSClassFromString(arrayObjectClassString)]) { [NSException raise:@"YOU MADE A MISTAKE" format:@"you tried to insert a %@ but I can only accept %@", [item class], arrayObjectClassString]; } else { if (!sortWithThisComparator) { [self.items addObject:item]; } else { NSInteger newItemIndex = [self.items indexOfObject:item inSortedRange:NSMakeRange(0, [self.items count]) options:NSBinarySearchingFirstEqual usingComparator:sortWithThisComparator]; if (newItemIndex >= [self.items count]) { [self.items addObject:items]; } else { [self.items insertObject:item atIndex:newItemIndex]; } } } }
Everything works fine when I do not install the comparator, but when I use the comparator, I get a bad access error:
typedef NSComparisonResult (^NSComparator)(id obj1, id obj2); ... [[CKGenericSingletonSubclass sharedManager] setSortWithThisComparator: ^NSComparisonResult(CKGeneralizedItemSubclass *i1, CKGeneralizedItemSubclass *i2) { NSLog(@"we are inside"); NSLog(@"here is the item 1 %@", i1); NSLog(@"we are comparing this float %f to thisf loat %f", i1.gradeSchoolAverage, i2.gradeSchoolAverage); if (i1.gradeSchoolAverage < i2.gradeSchoolAverage) { return NSOrderedAscending; } else if (i1.gradeSchoolAverage == i2.gradeSchoolAverage) { return NSOrderedSame; } else { return NSOrderedDescending; } }];
I get a bad access stream in the second line of the comparator, which simply registers one of the parameters passed through NSComparator. However, the instances of the class that I pass to insertItem are available elsewhere without this problem, so I know that they were created correctly and transferred correctly otherwise, since I can insert them into the items property without a comparator. What am I missing here?
Additional Information. I save NSComparator as
@property (strong, atomic) NSComparator sortWithThisComparator;
sorting objective-c nsarray exc-bad-access
sunny
source share