You should create a header file like
// Constants.h
FOUNDATION_EXPORT NSString *const MyFirstConstant;
FOUNDATION_EXPORT NSString *const MySecondConstant;
//etc.
(you can use extern
instead of FOUNDATION_EXPORT
if your code will not be used in mixed C/C++ environments or on other platforms)
You can include this file in each file that uses the constants or in the pre-compiled header for the project.
You define these constants in a .m file like
// Constants.m
NSString *const MyFirstConstant = @"FirstConstant";
NSString *const MySecondConstant = @"SecondConstant";
Constants.m should be added to your application/framework's target so that it is linked in to the final product.
The advantage of using string constants instead of #define
'd constants is that you can test for equality using pointer comparison (stringInstance == MyFirstConstant
) which is much faster than string comparison ([stringInstance isEqualToString:MyFirstConstant]
) (and easier to read, IMO).
Compare method
Either you implement a compare-method for your object:
- (NSComparisonResult)compare:(Person *)otherObject {
return [self.birthDate compare:otherObject.birthDate];
}
NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];
NSSortDescriptor (better)
or usually even better:
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"birthDate"
ascending:YES];
NSArray *sortedArray = [drinkDetails sortedArrayUsingDescriptors:@[sortDescriptor]];
You can easily sort by multiple keys by adding more than one to the array. Using custom comparator-methods is possible as well. Have a look at the documentation.
Blocks (shiny!)
There's also the possibility of sorting with a block since Mac OS X 10.6 and iOS 4:
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(Person *a, Person *b) {
return [a.birthDate compare:b.birthDate];
}];
Performance
The -compare:
and block-based methods will be quite a bit faster, in general, than using NSSortDescriptor
as the latter relies on KVC. The primary advantage of the NSSortDescriptor
method is that it provides a way to define your sort order using data, rather than code, which makes it easy to e.g. set things up so users can sort an NSTableView
by clicking on the header row.
Best Answer
You can implement
applicationShouldTerminateAfterLastWindowClosed:
to return YES in your app's delegate. But I would think twice before doing this, as it's really unusual on the Mac outside of small "utility" applications like Calculator and most Mac users will not appreciate your app behaving so strangely.