UIImage as Parameter: Unrecognized selector sent to instance - ios4

The code below is the image picker callback that runs after the user takes a photo with the camera / or picks a photo from the library.
Can someone explain to me why the first version works and second version throws an error?
The first version passes a UIImage from a synthesised UIImageView to method scaleAndRotateImage.
The second version declares a local UIImageView and passes the image to method scaleAndRotateImage.
This is the first version that works::
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
VC_Create_Preview *vc_create_preview = [[VC_Create_Preview alloc] initWithNibName:#"VC_Create_Preview" bundle:nil];
//UIImageView *temp = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
//temp.image = [self scaleAndRotateImage:temp.image];
//vc_create_preview.origImage = temp;
srcImageView.image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
srcImageView.image = [self scaleAndRotateImage:srcImageView.image];
vc_create_preview.origImage = srcImageView;
[self.navigationController pushViewController:vc_create_preview animated:YES];
}
But the 2nd version below does not, and throws an error when calling method scaleAndRotateImage (note in debug i cannot even step "into" scaleAndRotateImage)
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
VC_Create_Preview *vc_create_preview = [[VC_Create_Preview alloc] initWithNibName:#"VC_Create_Preview" bundle:nil];
UIImageView *temp = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
temp.image = [self scaleAndRotateImage:temp.image];
vc_create_preview.origImage = temp;
//srcImageView.image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
//srcImageView.image = [self scaleAndRotateImage:srcImageView.image];
//vc_create_preview.origImage = srcImageView;
[self.navigationController pushViewController:vc_create_preview animated:YES];
}
The error thrown by the 2nd version is
Pending breakpoint 1 - ""VC_Create_Capture.m":97" resolved
2012-01-04 20:33:52.674 MultiInterfaceTest[430:f803] -[UIImage image]: unrecognized selector sent to instance 0x68aac00
2012-01-04 20:33:52.717 MultiInterfaceTest[430:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImage image]: unrecognized selector sent to instance 0x68aac00'
*** First throw call stack:
(0x13c2052 0x1553d0a 0x13c3ced 0x1328f00 0x1328ce2 0x35df 0x211c52 0xbfaa305 0xbfbe5fd 0xc022fef 0x2dde39 0x2dd143 0x2de3cf 0x2e0a31 0x2e098c 0x2d93e7 0x41812 0x41ba2 0x28384 0x1baa9 0x12acfa9 0x13961c5 0x12fb022 0x12f990a 0x12f8db4 0x12f8ccb 0x12ab879 0x12ab93e 0x19a9b 0x23b8 0x2315)
terminate called throwing an exceptionCurrent language: auto; currently objective-c

"-[UIImage image]: unrecognized selector sent to instance 0x68aac00"
It seems that the [UIImageView image] accessor method gets called on an UIImage object. Most likely it's a memory management error: the UIImageView gets deallocated, and its memory is filled with the UIImage instance, erronously. (Unrelated: you're also leaking memory in the first approach. -pushViewController:animated: retains the view controller, so you must -release it.

This is because some where you have called image API on UIImage Class. image is a method of UIImageView class not UIImage. thats why Xcode is throwing this error.
To resolve it make sure that you are calling
So please sure that you are calling the image API on UIImage View class not UIImage. Check all the variables you have declare in your .h file and make sure you have used UIImageView class instead of UIImage.
Unrecongnized selector means that your class does not support the any image API that you have called inside your code.

Sorry Guys i found the answer.
The following is wrong because the [info objectForKey....] returns a UIImage, not a UIImageView.
Hence its probably that temp wasn't probably created hence an error from the 2nd line of the code.
UIImageView *temp = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
temp.image = [self scaleAndRotateImage:temp.image];
vc_create_preview.origImage = temp;
Thanks everyone!

Related

AVAudioEngine crash on connect node

I've setup my AVAudioEngine in its own method like this:
AVAudioSession* session = [AVAudioSession sharedInstance];
[session setPreferredSampleRate:[session sampleRate] error:nil];
[session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
[session setActive:YES error:nil];
audioEngine_ = [[AVAudioEngine alloc] init];
//tap the outputNode to create the singleton
[audioEngine_ outputNode];
NSError* error;
[audioEngine_ startAndReturnError:&error];
There is no error starting it up. I have another method to attach an AVAudioUnitMIDIInstrument from an AudioComponentDescription I've received from an Inter-App Audio instrument. My connect method looks like this:
-(void)connectInstrument:(AudioComponentDescription)desc {
instNode_ = nil;
instNode_ = [[AVAudioUnitMIDIInstrument alloc] initWithAudioComponentDescription:desc];
[audioEngine_ attachNode:instNode_];
//Crashes here
[audioEngine_ connect:instNode_ to:[audioEngine_ outputNode] format:nil];
[audioEngine_ startAndReturnError:nil];
NSLog(#"done connecting");
}
The crash gives me no useful information. I get this:
invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debug. This message will only appear once per execution.
* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndexedSubscript:]: index 0 beyond bounds for empty array'
If I do a test and try to create a new mixer node and attach/connect it, there is no crash.
I have more relevant information
If I do this:
AVAudioFormat* instFormat = [instUnit_ outputFormatForBus:0];
I get the same error:
-[__NSArrayM objectAtIndexedSubscript:]: index 0 beyond bounds for empty array
It's almost as though there is no AVAudioFormat set for any output busses, nor any input busses (I checked inputFormatForBus as well). This is odd because if I do:
AudioStreamBasicDescription f1;
UInt32 outsize = sizeof(f1);
AudioUnitGetProperty(instNode_.audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &f1, &outsize);
Then f1 is a valid AudioStreamBasicDescription showing a standard 44.1khz sample rate, 32 bit float, 2 channels. So there is an output stream format, but it doesn't seem to be attached to any output bus of the AVAudioUnitMIDIInstrument instance.
EDIT - Further information
Even if I just try to access instUnite_.name I get the NSRangeException. I'm wondering now if this is a problem with how I'm getting the component description. I'm attempting to use Inter-App Audio (I have done all of the proper entitlements, capabilities, and app ID setup). This is how I am discovering Inter-App Audio components:
NSMutableArray* units = [[NSMutableArray alloc] init];
AudioComponentDescription searchDesc = { kAudioUnitType_RemoteInstrument, 0, 0, 0, 0 };
NSArray* componentArray = [[AVAudioUnitComponentManager sharedAudioUnitComponentManager] componentsMatchingDescription:searchDesc];
for(AVAudioUnitComponent* component in componentArray) {
AudioComponentDescription description = component.audioComponentDescription;
InterAppAudioUnit* unit = [[InterAppAudioUnit alloc] init];
unit.componentDescription = description;
unit.icon = AudioComponentGetIcon(component.audioComponent, 44.0f);
unit.name = component.name;
unit.avComponent = component;
[units addObject:unit];
}
_units = units;
[self.tableView reloadData];
This is all in a presented UITableViewController. After clicking one I simply execute:
[self connectInstrument:unit.componentDescription];
If I instead hand build a component description for a local unit, the AVAudioUnit is instantiated just fine and nothing crashes.
I found the answer. The AUAudioUnit object inside of the AVAudioUnit object has no output busses upon creation. I'm not sure why. You can fix it by doing this:
AUAudioUnit* auInst = instUnit_.AUAudioUnit;
NSMutableArray<AUAudioUnitBus*>* busArray = [[NSMutableArray alloc] init];
AVAudioFormat* outFormat = [[self->audioEngine_ outputNode] outputFormatForBus:0];
AUAudioUnitBus* bus = [[AUAudioUnitBus alloc] initWithFormat:outFormat error:&err];
[busArrays addObject:bus];
[[auInst outputBusses] replaceBusses:busArray];

GPUImage terminates due to [AVAssetWriter startWriting] Cannot call method when status is 3'

I am having an issue running GPUImage. I have modified SimpleVideoFileFilter program(replaced the filter with a chromakeyfilter) and am using my own video. My program is terminating due to the following error:
[AVAssetWriter startWriting] Cannot call method when status is 3'
I have gone through the forums but not sure why the moviewriter is closing and then someone is writing to it.
I am using iPhone4 running iOS 7.0
Any clues are greatly appreciated. Thanks much!
Check whether your destination file exists already. If it does, remove it.
I was trying to add the file to a directory which did not exist. Example : /Videos/Video.mov , leaving it just /Video.mov worked.
Ok, I have a few ideas for you.
When you say "it just shows a frame and never plays the video" we have a good indication that your entire processing pipeline from start to finish is functional exactly once, then stops working.
That tells us that you are stringing things together correctly, but some of the components don't exist longer than a single frame buffer cycle, and subsequently the whole process stops.
it looks like filter and movieWriter are scoped to the class (I'm assuming they're not properties from the lack of an underscore, _filter and _movieWriter). So they will live on after this method has finished (correct me if I'm wrong...)
I think where you are encountering trouble is your (GPUImageView*)displayView
This should probably be declared as a class property (although it could work as just a variable) and then instantiated through the nib or the viewDidLoad method of the view controller.
As you have it now, this line: GPUImageView* filterView = (GPUImageView*)displayView; is making an assignment for filterView which is not used (and therefore unnecessary). It's not clear if displayView really is an instance of GPUImageView or if it will still be in existence when the current method finishes. (in fact you say it "is a UIView that I have programmatically created")
displayView will have to be a subclass of GPUImageView for this whole thing to work, and it will have to be scoped to the class, and not the method.
Declare it like this:
#property (strong, nonatomic)GPUImageView* displayView;
and then instantiate it and add it to your view hierarchy from within viewDidLoad
movieFile1 = [[GPUImageMovie alloc] initWithURL:movieFileURL1];
movieFile2 = [[GPUImageMovie alloc] initWithURL:movieFileURL2];
movieFile2.runBenchmark = YES;
movieFile2.playAtActualSpeed = NO;
filter = [[GPUImageChromaKeyBlendFilter alloc] init];
[(GPUImageChromaKeyBlendFilter *)filter setColorToReplaceRed:0.0 green:1.0 blue:0.0];
[(GPUImageChromaKeyBlendFilter *)filter setThresholdSensitivity:0.4];
GPUImageView *filterView = (GPUImageView*)displayView;
[filter addTarget:displayView];
[movieFile1 addTarget:filter];
[movieFile2 addTarget:filter];
NSString *pathToMovie = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Movie.m4v"];
unlink([pathToMovie UTF8String]);
NSURL *movieURL = [NSURL fileURLWithPath:pathToMovie];
movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:movieURL size:CGSizeMake(1920.0, 1280.0)];
[filter addTarget:movieWriter];
movieWriter.shouldPassthroughAudio = YES;
movieFile1.audioEncodingTarget = movieWriter;
[movieFile1 enableSynchronizedEncodingUsingMovieWriter:movieWriter];
[movieWriter startRecording];
[movieFile1 startProcessing];
[movieFile2 startProcessing];
[movieWriter setCompletionBlock:^{
[filter removeTarget:movieWriter];
[movieWriter finishRecording];
}];
if (outputPath) {
finalURL = [[stongObj tempFileURL] copy];
DebugLog(#"Start Filter Processing :%#",finalURL);
DebugLog(#"movieUrl :%#",movieUrl);
// [CSUtils removeChuckFilePaths:#[outputPath]];
//Create Image Movie Object
_movieFile = [[GPUImageMovie alloc] initWithURL:outputPath];
//_movieFile = [[GPUImageMovie alloc] initWithURL:[[NSBundle mainBundle] URLForResource:#"videoviewdemo" withExtension:#"mp4"]];
_movieFile.runBenchmark = NO;
_movieFile.playAtActualSpeed = YES;
_movieFile.delegate = self;
//Movie Writer Object
_movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:finalURL size:CGSizeMake([UIScreen mainScreen].bounds.size.height,[UIScreen mainScreen].bounds.size.height)];
//_movieWriter.delegate = self;
//Create Selecetive GPU Image Filter
[stongObj setGpuOutputFilter:selectedVideoFilterType];
//Create Group Filter
groupFilter = [[GPUImageFilterGroup alloc] init];
[groupFilter addTarget:imageOutputFilter];
// Only Single Filter is implemented.
//Apply Initial and Terminal Filter
[(GPUImageFilterGroup *)groupFilter setInitialFilters:[NSArray arrayWithObject:imageOutputFilter]];
[(GPUImageFilterGroup *)groupFilter setTerminalFilter:imageOutputFilter];
//_movieWriter -> groupFilter ->_movieFile
[_movieFile addTarget:groupFilter];
[groupFilter addTarget:_movieWriter];
_movieWriter.shouldPassthroughAudio = YES;
_movieFile.audioEncodingTarget = _movieWriter;
[_movieFile enableSynchronizedEncodingUsingMovieWriter:_movieWriter];
//Start Recording
[_movieWriter startRecording];
//Start Processing
[_movieFile startProcessing];
__weak typeof(self) weekSelf=self;
[_movieWriter setCompletionBlock:^{
__strong typeof(self) stongSelf=weekSelf;
DebugLog(#"Movie Write Completed");
//Finish Recording.
[stongSelf.movieWriter finishRecording];
//Release all object
// [self releaseAllObject];
//remove movieUrl,audioUrl,outputPath
[CSUtils removeChuckFiles:#[movieUrl,audioUrl,outputPath]];
}];
[_movieFile startProcessing]; app get crash in iOS 8 on this line but working fine on iOS 7
#Seasia Creative ,I have no enough reputation to add a comment by that list,I create a new list to answer U.
I check the output URL,console log "/var~~~~/tmpmerge.mp4",so i realize that ,i miss a "/" --->"/var~~~~/tmp/merge.mp4".
If the url is no correct, project runs into the same error.
hope to help some.

Presenting UITabBarController Modally - Autorotate Problem

I'm attempting to present a UITabBarController modally using the following code:
// Declare all view controllers.
TabOne *tabOne = [[TabOne alloc] initWithNibName:#"TabOne" bundle:nil];
TabTwo *tabTwo = [[TabTwo alloc] init];
TabThree *tabThree = [[TabThree alloc] init];
// Set each view controller's delegate to self.
tabOne.delegate = self;
tabTwo.delegate = self;
tabThree.delegate = self;
// Set a title for each view controller.
tabOne.title = #"One";
tabTwo.title = #"Two";
tabThree.title = #"Three";
// Create a tab bar controller.
UITabBarController *tabBarController = [[UITabBarController alloc] init];
[tabBarController setViewControllers:[NSArray arrayWithObjects:tabOne,tabTwo,tabThree, nil]];
// Present the tab bar controller modally.
[self presentModalViewController:tabBarController animated:NO];
// Memory management.
[tabOne release];
[tabTwo release];
[tabThree release];
This all works as expected except that I get the following warnings in the console:
Using two-stage rotation animation. To use the smoother single-stage animation, this application must remove two-stage method implementations.
Using two-stage rotation animation is not supported when rotating more than one view controller or view controllers not the window delegate.
I've done some research on this and have checked that shouldAutorotateToInterfaceOrientation is implemented as follows:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
As far as I can tell, the problem is that the tab bar controller is not the root view controller, but I'm presenting this modal view some way into a deep view hierarchy. It's called from another modal view, which itself is called from a tab bar set in the application delegate.
I know this is a bit of an old chestnut, but it's got me stumped. Any thoughts?
Thanks in advance.
I've had a similar problem.
UITabBarController has some odd behavior with its orientation handling. When setting its orientation, it calls recursively into self.selectedViewController to decide whether to use one-stage or two-stage animation. That seems sensible, but the trouble is self.selectedViewController is initially nil (in particular, if you're displaying the UITabBarController modally for the first time), and that can confuse the controller. Depending on the iOS version, a nil selectedViewController will lead the UITabBarController to believe that one-stage animation is unsupported.
Try this: when you first load / initialize your UITabBarController, add the line
tabBarController.selectedIndex = 0;
I was getting this warning (including serious visual problems: the view controller was switching orientation but the status bar was not), and setting the index this way fixed the problem. The UITabBarController successfully called into its selected view controller, and detected the one-stage animation.

How to "preload" view controller without actually pushing it?

Background:
I've got a free app that is ad-supported. The basic idea is that when the app is launched, ad content (HTML) is downloaded from the server in the background, and only if the download was successful, then the content is being shown.
Previous solution:
I have implemented this successfully in a universal app. Originally, I loaded a NSData variable with an URL, and if it was successful, then I presented a modal view which contained an UIWebView (relevant code is in another question). The problem is that the external assets (images) don't get loaded in the original NSData request, so in a stroke of genius I thought of another way:
New solution:
The new way, and this is what I want help with, is that I'm instantiating the modal view controller (without displaying it yet), and having the web view begin loading the URL directly. When the webViewDidFinishLoad method is called, I fire a notification back to the parent which then performs the presentModalViewController.
Here are the methods which instantiate the view controller and present it modally:
- (void)launchAd
{
if ([ServerCheck serverReachable:#"openx.freewave-wifi.com" hideAlert:YES])
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(presentAdModal) name:#"AdLoaded" object:nil];
AdViewController *adView = [[AdViewController alloc] initWithNibName:nil bundle:nil];
[[adView view] awakeFromNib]; //THIS LINE IS WHAT THIS QUESTION IS ABOUT
navController = [[UINavigationController alloc] initWithRootViewController:adView];
[adView release], adView = nil;
[navController setModalPresentationStyle:UIModalPresentationFormSheet];
[navController setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
[[navController navigationBar] setTintColor:[UIColor colorWithRed:0.94 green:0.00 blue:0.32 alpha:1.00]];
}
else
LogError(#"Not presenting ad.");
}
- (void)presentAdModal
{
LogInfo(#"Presenting advertisement modal.");
[[NSNotificationCenter defaultCenter] removeObserver:self name:#"AdLoaded" object:nil];
[tabBarController presentModalViewController:navController animated:YES];
[navController release];
}
And in the AdView controller:
- (void)webViewDidFinishLoad:(UIWebView *)theWebView
{
LogInfo(#"Ad content did load; we can show it.");
[timeout invalidate], timeout = nil;
[self setTitle:#"From Our Sponsor"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"AdLoaded" object:nil];
}
Now what's above does work. However, it took a long time for me to figure out how to cause the view controller delegate methods in the AdView controller to fire before calling presentModalViewController. I did this by adding [[adView view] awakeFromNib];, but I know this isn't the right way to make this happen.
So, everything above does work beautifully, effectively having the view controller and its UIWebView "preload" before displaying it. I just want to know what I should be doing instead of [[adView view] awakeFromNib]; -- I want to do it the right way.
Or is this right? I guess some folks would say "If it works, then it's right", but I know this isn't true.

Why is my app crashing when I modify a Core Data relationship in an NSOperation subclass?

Background
I've got the following tree of objects:
Name Project
Users nil
John nil
Documents nil
Acme Project Acme Project <--- User selects a project
Proposal.doc Acme Project
12:32-12:33 Acme Project
13:11-13:33 Acme Project
...thousands more entries here...
The user can assign a group to a project. All descendants get set to that project.
This locks up the main thread so I'm using NSOperations.
I'm using the Apple approved way of doing this, watching for NSManagedObjectContextDidSaveNotification and merging into the main context.
The Problem
My saves have been failing with the following error:
Failed to process pending changes before save. The context is still dirty after 100 attempts. Typically this recursive dirtying is caused by a bad validation method, -willSave, or notification handler.
What I've Tried
I've stripped all the complexities of my app away, and made the simplest project I could think of. And the error still occurs. I've tried:
Setting the max number of operations on the queue to 1 or 10.
Calling refreshObject:mergeChanges: at several points in the NSOperation subclass.
Setting merge policies on the managed object context.
Build and Analyze. It comes up empty.
My Question
How do I set relationships in an NSOperation without my app crashing? Surely this can't be a limitation of Core Data? Can it?
The Code
Download my project: http://synapticmishap.co.uk/CDMTTest1.zip
Main Controller
#implementation JGMainController
-(IBAction)startTest:(id)sender {
NSManagedObjectContext *imoc = [[NSApp delegate] managedObjectContext];
JGProject *newProject = [JGProject insertInManagedObjectContext:imoc];
[newProject setProjectName:#"Project"];
[imoc save];
// Make an Operation Queue
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue setMaxConcurrentOperationCount:1]; // Also crashes with a higher number here (unsurprisingly)
NSSet *allTrainingGroupsSet = [imoc fetchAllObjectsForEntityName:#"TrainingGroup"];
for(JGTrainingGroup *thisTrainingGroup in allTrainingGroupsSet) {
JGMakeRelationship *makeRelationshipOperation = [[JGMakeRelationship alloc] trainGroup:[thisTrainingGroup objectID] withProject:[newProject objectID]];
[queue addOperation:makeRelationshipOperation];
makeRelationshipOperation = nil;
}
}
// Called on app launch.
-(void)setupLotsOfTestData {
// Sets up 10000 groups and one project
}
#end
Make Relationship Operation
#implementation JGMakeRelationshipOperation
-(id)trainGroup:(NSManagedObjectID *)groupObjectID_ withProject:(NSManagedObjectID *)projectObjectID_ {
appDelegate = [NSApp delegate];
imoc = [[NSManagedObjectContext alloc] init];
[imoc setPersistentStoreCoordinator:[appDelegate persistentStoreCoordinator]];
[imoc setUndoManager:nil];
[imoc setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(mergeChanges:)
name:NSManagedObjectContextDidSaveNotification
object:imoc];
groupObjectID = groupObjectID_;
projectObjectID = projectObjectID_;
return self;
}
-(void)main {
JGProject *project = (JGProject *)[imoc objectWithID:projectObjectID];
JGTrainingGroup *trainingGroup = (JGTrainingGroup *)[imoc objectWithID:groupObjectID];
[project addGroupsAssignedObject:trainingGroup];
[imoc save];
trainingGroupObjectIDs = nil;
projectObjectID = nil;
project = nil;
trainingGroup = nil;
}
-(void)mergeChanges:(NSNotification *)notification {
NSManagedObjectContext *mainContext = [appDelegate managedObjectContext];
[mainContext performSelectorOnMainThread:#selector(mergeChangesFromContextDidSaveNotification:)
withObject:notification
waitUntilDone:YES];
}
-(void)finalize {
appDelegate = nil;
[[NSNotificationCenter defaultCenter] removeObserver:self];
imoc = nil;
[super finalize];
}
#end
#implementation NSManagedObjectContext (JGUtilities)
-(BOOL)save {
// If there's an save error, I throw an exception
}
#end
Data Model
Update 1
I've experimented some more, and even without the merge, the exception is still thrown. Just saving the managed object context in another thread after modifying a relationship is enough.
I have a shared persistent store coordinator with the app delegate. I've tried making a separate NSPersistentStoreCoordinator for the thread with the same URL as my data store, but Core Data complains.
I'd love to suggestions on how I can make a coordinator for the thread. The core data docs allude to there being a way of doing it, but I can't see how.
You are crossing the streams (threads in this case) which is very bad in CoreData. Look at it this way:
startTest called from a button (is IBAction, assuming button tap) on Main thread
Your for loop creates a JGMakeRelationship object using the initializer trainGroup: withProject: (this should be called init, and probably call super, but that's not causing this issue).
You create a new managed object context in the operation, on the Main thread.
Now the operation queue calls the operations "main" method from a worker thread (put a breakpoint here and you'll see it's not on the main thread).
Your app goes boom because you've accessed a Managed object Context from a different thread than the one you created it on.
Solution:
Initialize the managed object context in the main method of the operation.

Resources