I have a sorting comparator which I need to use in a few different ViewControllers so I’m trying to keep it in a separate file. I’ve read I should be able to put the sorting block in a separate file, but which ever method I try I seem to get “unrecognized selector sent to instance”. The code I have is:
#import <Foundation/Foundation.h>
typedef NSComparator (^IntBlock)(id obj1, id obj2);
@interface Utils : NSObject {
NSComparator SortObjNameComparer;
NSComparator SortObjPriceComparer;
}
@property (readwrite, copy) NSComparator SortObjNameComparer;
@property (readwrite, copy) NSComparator SortObjPriceComparer;
To sort this I’m using
Utils *comp = [[Utils alloc] init];
if(segmentedControl.selectedSegmentIndex == 0){
self.productArray = [self.productArray sortedArrayUsingComparator:[comp SortObjNameComparer] context:nil]; //EXC_BAD_ACCESS
} else if(segmentedControl.selectedSegmentIndex == 1){
self.productArray = [self.productArray sortedArrayUsingComparator:[Utils SortObjPriceComparer]];// EXC_BAD_ACCESS
Is there a clean way to do this?
Another way to do this is to create a C function that returns a block. That way you can create this block wherever you like:
e.g
MyComparator.h
MyComparator.m
And then all you need to do it use these is to import the header and use it as:
Saves having to go through the whole Object creation and property route.
Note that I’m using the
Createnaming convention to remind me that I have to release the object myself when I’m done with it.