To make the app store the last few PIDs in an array in the user defaults, I wrote the following updateLastPids method. First, make sure to do, say,
#define kMaxNumberOfPids 5 //should be integer greater than zero!
#define ENLastPidsUserDefault @"ENLastPidsUserDefault";
By the way, I'm using 5 because I'm gonna let the app send me the logs for the last 5 runs, just in case the crash was a result of something getting messed up even earlier than on the last run; you can change 5 to 1 if you wish.
- (void)updateLastPids
{
NSInteger currentPid = [[NSProcessInfo processInfo] processIdentifier];
NSNumber *currentPidNumber = [NSNumber numberWithInt:currentPid];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *lastPidsArray = [[userDefaults arrayForKey:ENLastPidsUserDefault]
mutableCopy];
if (!lastPidsArray)
{
NSArray *newLastPidsArray = [NSArray arrayWithObject:currentPidNumber];
[userDefaults setObject:newLastPidsArray forKey:ENLastPidsUserDefault];
}
else
{
if ([lastPidsArray count] == kMaxNumberOfPids)
{
[lastPidsArray removeObjectAtIndex:0]; //get rid of the oldest PID
[lastPidsArray addObject:currentPidNumber];
NSAssert([lastPidsArray count] == kMaxNumberOfPids, @"invalid count");
}
//In case I decrease kMaxNumberOfPids later on. (Or some PITA user added
//stuff into the array by himself or herself!)
else if ([lastPidsArray count] > kMaxNumberOfPids)
{
[lastPidsArray removeObjectAtIndex:0];
while ([lastPidsArray count] >= kMaxNumberOfPids)
[lastPidsArray removeLastObject];
[lastPidsArray addObject:currentPidNumber];
NSAssert([lastPidsArray count] == kMaxNumberOfPids, @"invalid count");
}
else
{
[lastPidsArray addObject:currentPidNumber];
NSAssert([lastPidsArray count] <= kMaxNumberOfPids, @"invalid count");
}
[userDefaults setObject:lastPidsArray forKey:ENLastPidsUserDefault];
}
}
In my next answer I will show how I used the ASL Cocoa wrapper to get the console logs from the last PIDs (the PIDs should now be in the user defaults after running the above method).