RestKit with CoreData crashes - core-data

I am new to CoreData and just started working with RestKit. I am trying to create a Restkit project with CoreData. But I am getting this runtime error:
Assertion failure in +[NSManagedObject managedObjectContext]
Any ideas, what I am doing wrong?
Following is my code so far. I have not created a data model as of now.
_objectManager = [RKObjectManager objectManagerWithBaseURL:#"https://api.foursquare.com/v2/venues"];
// _objectManager.objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:#"jiffAssignment.sqlite"];
RKManagedObjectMapping *locationMapping = [RKManagedObjectMapping mappingForClass:[Location class]];
[locationMapping mapKeyPath:#"address" toAttribute:#"address"];
[locationMapping mapKeyPath:#"crossStreet" toAttribute:#"crossStreet"];
[locationMapping mapKeyPath:#"city" toAttribute:#"city"];
[locationMapping mapKeyPath:#"state" toAttribute:#"state"];
[_objectManager.mappingProvider setMapping:locationMapping forKeyPath:#"location"];
// RKObjectMapping *statisticsMapping = [RKManagedObjectMapping mappingForClass:[Statistics class]];
// [statisticsMapping mapAttributes:#"checkinsCount",#"usersCount", nil];
NSLog(#"VenueListController Initialized");
return self;
Any help/comments would be appreciated.
Thanks
Vik

Can you update your post with the actual assertion that fails?
And you shouldn't be able to use an RKManagedObjectMapping if _objectManager doesn't have an objectStore set. This line is commented out in the code you posted.

Related

App crashes with one attribute of core data

I have a pretty weird problem. I'm using coredata to save notes. I can access/save/edit all the attributes of the "Notes" entity, besides one : category.
-(void)editCategory {
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *categRequest = [NSEntityDescription entityForName:#"Notes" inManagedObjectContext:_managedObjectContext];
request.predicate = [NSPredicate predicateWithFormat:#"text = %#", noteToEdit];
[request setEntity:categRequest];
//Error handling
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[_managedObjectContext executeFetchRequest:request error:&error]mutableCopy];
if (mutableFetchResults == nil) {
NSLog(#"Error happened : %#", error);
}
Notes *editMe = [mutableFetchResults objectAtIndex:0];
[editMe setCategory:editCategoryText];
NSLog(#"Category from pickerview : %#", editCategoryText);
if (![_managedObjectContext save:&error]) {
NSLog(#"couldnt save : %#", error);
}
}
This line :
[editMe setCategory:editCategoryText];
is crashing. editCategoryText is a string, as the category attribute. The weird thing is that I'm using the exact same piece of code to change the title attribute, and I don't have any problem.
Log file :
2013-11-07 15:49:20.286 Simple Notes 1[16511:a0b] -[__NSCFString managedObjectContext]: unrecognized selector sent to instance 0x8dccc30
2013-11-07 15:49:20.293 Simple Notes 1[16511:a0b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString managedObjectContext]: unrecognized selector sent to instance 0x8dccc30'
Do you have any idea why this attribute is behaving differently from the others ? Thank you.
Not at a computer so can't test this but:
Get rid of the mutableCopy. executeFetchRequest returns autoreleased objects, which you are then trying to copy, this turns into a garbage pointer, which happens to end up pointing to a string.
Actually it seems like it was a core data bug, I solved it by deleting my app in the simulator, deleting the core data model in xcode, built it again and performed a clean.

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.

RestKit / Core Data: Remotely deleted entities get not removed from Core Data

Why do remotely deleted entities not removed from Core Data and the datastore? Setting a breakpoint at the beginning of
- (void)deleteCachedObjectsMissingFromResult:(RKObjectMappingResult *)result
in RKManagedObjectLoader shows up that the variable result does not contain anything.
I could fix that problem by implementing this feature in the RestKit delegate - (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects but that is kind of unclean code in my point of view. RestKit / Core Data should do that by itself?! Anyway, following implementation would solve the problem:
- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects
{
NSArray *allReservations = [Reservation findAll];
for(Reservation *reservationRecord in allReservations) {
if(![objects containsObject:reservationRecord]) {
[[[[RKObjectManager sharedManager] objectStore] managedObjectContextForCurrentThread] deleteObject:reservationRecord];
}
}
}
any ideas to solve that problem without the help of didLoadObjects? Adding / updating existing entities works properly.
RestKit will only delete the entries in the NSManagedObjectContext. Your method only edits the objects in the NSManagedObjectContext but never saves them to the objectStore. Make sure to save the changes to the ObjectStore after the adding/editing/deleting has been finished.
- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects
{
NSArray *allReservations = [Reservation findAll];
// Deleting each item in NSManagedObjectContext
for(Reservation *reservationRecord in allReservations) {
if(![objects containsObject:reservationRecord]) {
[[[RKObjectManager sharedManager] objectStore] managedObjectContextForCurrentThread] deleteObject:reservationRecord];
}
}
// Changes only exist in NSManagedObjectContext, delete them in the ObjectStore
NSError *error = nil;
if (![[[RKObjectManager sharedManager] objectStore] managedObjectContextForCurrentThread] save:&error])
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}

mapping model is NULL - core data migration

I follow this nice tutorial http://mipostel.com/index.php/home/70-core-data-migration-standard-migration-part-2 to do my core data migration.
For some strange reason i always get NULL in the mappingModel in these lines:
NSMappingModel *mappingModel = [NSMappingModel mappingModelFromBundles:nil
forSourceModel:sourceModel
destinationModel:destinationModel];
(line 191 in the linked code)
I tried to create a very simple derived version of the model, I recreated a mappingModel a 1000 times, made sure that the mapping model file is in the project directory - but this call always returns NULL.
Anybody has an idea what is wrong here?
ps I was just wondering that setting the migration options is called AFTER the mapping Model is used.
NSURL *storeUrl = [NSURL fileURLWithPath:storePath];
NSError *error;
NSDictionary *pscOptions = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:NO], NSInferMappingModelAutomaticallyOption,
nil];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeUrl
options:pscOptions
error:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
(lines 123...)
Anyway
Why can't the mapping model be found ?
pss couldn't help holding back :-) this core data migration stuff is much too complicated and difficult compared to doing simple SQL DB migration - wasting soooo much time.
So a BIG THANKS in advance!
I followed that same tutorial and ended up having to manualy open my mapping model by URL
NSString *mappingModelPath = [[NSBundle mainBundle] pathForResource:#"mappingModel10" ofType:#"cdm"];
NSLog(#"mapping model path:%#", mappingModelPath);
NSURL *mappingModelUrl = [NSURL fileURLWithPath:mappingModelPath];
NSMappingModel *mappingModel = [[NSMappingModel alloc] initWithContentsOfURL:mappingModelUrl];
I found the file name for my mapping model by looking in my App's bundle.

iOS Core Data how to properly initialize entity relationships?

I have a one to many relationship in my core data model. I need to create a new entity and save it. The entity has a one to many relationship which generated the following code:
- (void)addRelationshipEvent1:(NSSet *)values;
- (void)removeRelationshipEvent1:(NSSet *)values;
.
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
ApplicationRecord *newManagedObject = (ApplicationRecord*)[NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
newManagedObject.startDate = [NSDate date];
newManagedObject.stopDate = [[NSDate date] dateByAddingTimeInterval:120];
//keep adding individual dynamic properties
is it correct to set the -toMany relationship sets to nil initially? Or do I need to initialize an (empty?) set here and assign it? Would I be able to add extra objects later if I set the initial set to nil?
newManagedObject.relationshipEvent1 = nil;
newManagedObject.relationshipEvent2 = nil;
//...
// Save the context.
NSError *error = nil;
if (![context save:&error])
{
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
Alex,
You don't need to intialize your relationships. Just use the supplied accessors or helper functions and Core Data takes care of it. IOW, only worry about the property/relationship when you need to actually use it.
Andrew

Resources