I am trying to save a video to core data but it is not working. When I added a break point it stopped on NSData *videoData = [NSData dataWithContentsOfUrl:self.videoURL]; What should I do to solve this.
Here is the code I am using to save the video:
- (void) saveVideo {
NSManagedObjectContext *context = [self managedObjectContext];
TimeTravelFeed *timeTravelFeed = [NSEntityDescription insertNewObjectForEntityForName:#"TimeTravelFeed" inManagedObjectContext:context];
NSData *videoData = [NSData dataWithContentsOfUrl:self.videoURL];
[timeTravelFeed setValue:videoData forKey:#"videoData"];
NSError *error = nil;
if (![self.managedObjectContext save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
Here is the error:
+[NSData dataWithContentsOfUrl:]: unrecognized selector sent to class 0x3b2947f4
2013-12-08 12:31:57.078 App Name[203:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[NSData dataWithContentsOfUrl:]: unrecognized selector sent to class 0x3b2947f4'
Your error is due to the fact that dataWithContentsOfUrl: is not a method of NSData, dataWithContentsOfURL: (capital R and L) is.
More importantly though is the fact that you shouldn't be saving the entire video into Core Data, you should save the video file to disk and store the file URL to Core Data instead.
Related
I have the following code:
-(void) saveFromLocationsArray: (NSArray*) locations{
[self.photoLib performChanges:^{
PHAssetChangeRequest *creationRequest;
NSMutableArray *changesArray = [[NSMutableArray alloc] init];
for(int i=0; i<locations.count; i++){
creationRequest = [PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:locations[i]];
[changesArray addObject:[creationRequest placeholderForCreatedAsset]];
}
PHAssetCollectionChangeRequest *collectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:self.objcAppAlbum];
[collectionChangeRequest addAssets:changesArray];
} completionHandler:^(BOOL success, NSError *error) {
if(!success){
NSLog(#"an error has occured while trying to save pic to library: %#", error);
}
else{
NSLog(#"image was added to album ObjcApp");
}
}];
In a nutshell: I have an array of locations (URLS) of images I've just downloaded, and I'm trying to add them all to the iPhone's photo library. i managed to do so for one image (in a different method) but here it crashes on [collectionChangeRequest addAssets:changesArray], my guess is that the argument fo addAssest is invalid... but i can't figure out why.
this is the working code for one image only:
-(void) saveFromLocation: (NSURL*) location{
[self.photoLib performChanges:^{
PHAssetChangeRequest *creationRequest = [PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:location];
PHAssetCollectionChangeRequest *collectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:self.objcAppAlbum];
NSArray *arr = [NSArray arrayWithObjects:[creationRequest placeholderForCreatedAsset], nil];
[collectionChangeRequest addAssets:arr];
} completionHandler:^(BOOL success, NSError *error) {
if(!success){
NSLog(#"an error has occured while trying to save pic to library: %#", error);
}
else{
NSLog(#"image was added to album ObjcApp");
}
}];
}
error: 2019-03-05 14:26:26.062368 ObjcProject[1026:371314]
-[__NSCFString path]: unrecognized selector sent to instance 0x1740fa880 2019-03-05 14:26:26.063343 ObjcProject[1026:371314] *
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[__NSCFString path]:
unrecognized selector sent to instance 0x1740fa880'
* First throw call stack: (0x186d3d1b8 0x18577455c 0x186d44268 0x186d41270 0x186c3a80c 0x19276338c 0x192700ee8 0x19275e8c4
0x19275edfc 0x1914ae4b8 0x191d49c4c 0x19275e510 0x192738be4
0x1914a0ddc 0x1001dd258 0x1001dd218 0x1001eaaec 0x1001e0ce0
0x1001eb088 0x1001ece2c 0x1001ecb78 0x185dcf2a0 0x185dced8c)
libc++abi.dylib: terminating with uncaught exception of type
NSException
I have an iOS 7 only app which uses Core Data for storage and I am bringing iCloud, with a switch to the app.
Every aspect of the iCloud integration is working, except the migration from the iCloud Store to the Local store if the user turns off iCloud from within the app.
Through the use of an Exception Breakpoint, the app is crashing with:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM replaceObjectAtIndex:withObject:]: object cannot be nil'
This is crashing at the "migratePersistentStore" code.
This is the code that performs that:
- (void)migrateiCloudStoreToTheLocalStoreAfterUserTurnedOffiCloudInSettings
{
// So we can see what's going on, we'll write out the current store URL before the migration
NSURL *storeURL = [self.persistentStoreCoordinator.persistentStores.lastObject URL];
NSLog(#"Current Store URL (before iCloud to Local migration): %#", [storeURL description]);
// NSPersistentStore *currentStore = self.persistentStoreCoordinator.persistentStores.lastObject;
NSPersistentStore *currentStore = [[self.persistentStoreCoordinator persistentStores] firstObject];
// We'll create a new URL
NSURL *localURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"Envylope.sqlite"];
NSDictionary *localStoreOptions = nil;
localStoreOptions = #{ NSPersistentStoreRemoveUbiquitousMetadataOption : #YES,
NSMigratePersistentStoresAutomaticallyOption : #YES,
NSInferMappingModelAutomaticallyOption : #YES};
NSError *error = nil;
[self.persistentStoreCoordinator migratePersistentStore:currentStore
toURL:localURL
options:localStoreOptions
withType:NSSQLiteStoreType error:&error];
NSLog(#"Current Store URL (after iCloud to Local migration): %#", [localURL description]);
// We'll write out a NSError here to see if there were any errors during the migration
NSLog(#"Error from iCloud to local migration %#", error);
// We'll just do a quick check to make sure are no errors with this procedure.
NSLog(#"Erros's after all of that %#", error);
NSLog(#"Current Store URL (after everything): %#", [localURL description]);
[self removeCloudObservers];
}
Issue
The app will crash, with the error above, at the migratePersistentStore line above. I cannot figure out what to do to get this working.
The commented out code for the currentStore shows that I've also tried checking for the lastObject, instead of the firstObject, and in both cases, I'm getting the same result.
I don't get any crashes from the local to iCloud because I want to make sure, if the user is using iCloud but then chooses not to, their data should be migrated locally.
This (Migrate Persistant Store Crash) Stack Overflow question seems like it would be a perfect fit, but firstly the answer isn't accepted and there's no confirmation that the code works from the person asking the question and also, that code didn't work for me; it simply removed the data.
Any guidance on this would really be appreciated.
With paying close attention to the link : Migrate Persistant Store Crash, I was able to get this working with the following code:
NSPersistentStoreCoordinator * persistentStoreCoordinator = self.persistentStoreCoordinator;
NSPersistentStore * persistentStore = [[persistentStoreCoordinator persistentStores] firstObject];
if([[NSFileManager defaultManager]fileExistsAtPath:localURL.path])
{
NSLog(#"File exists");
[[NSFileManager defaultManager] removeItemAtPath:localURL.path error:&error];
NSLog(#"Removing error = %#", error);
}
[[NSFileManager defaultManager] copyItemAtPath:persistentStore.URL.path toPath:localURL.path error:&error];
NSLog(#"The copying error = %#", error);
NSPersistentStoreCoordinator * newPersistentStoreCoordinator;
newPersistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
[newPersistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:localURL
options:localStoreOptions
error:&error];
NSLog(#"The adding error = %#", error);
Hopefully this will help someone with the same issue
I am using RestKit with Coredata and fetching data from the server and displaying.
Now I am doing a post from the client and this object gets updated as part of the response that comes back from the server. This is where the problems starts.
I looked for the correct way to implement this and came across 2 main points.
MOCs should not be shared across threads
An object created in the MOC is not available in another thread without saving.
But i think since the record gets updated from server response, its no longer finding the orig object. I just dont knw what the right fix is.
Here is my code
1. Create local entity
NSEntityDescription *itemEntity = [NSEntityDescription entityForName:ENTITY_ITEM inManagedObjectContext:self.managedObjectContext];
Item *item = [[Item alloc]initWithEntity:itemEntity insertIntoManagedObjectContext:self.managedObjectContext];
// Set params on item here
// Then save it
NSError *error = nil;
if (![self.managedObjectContext save:&error]) {
DBGLog(#"Tried to save the new item but failed - error %#, %#", error, [error userInfo]);
}
// Then I make the RestKit call to post the item
// The server updates the item Id
[SharedManager postItem:item success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
// successful case
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
// failure case
}];
It looks like when its trying to make the response it doesnt find the object.
And i get this exception -
*** Terminating app due to uncaught exception 'NSObjectInaccessibleException', reason: 'CoreData could not fulfill a fault for '0x156c87b0 <x-coredata://A42ABF18-01B6-4D78-B81B-62D8B604EB52/Item/p6>''
*** First throw call stack:
(0x2f853f0b 0x39feace7 0x2f5b7fd1 0x2f61a655 0x2f6246a7 0x2f6326e5 0x2f632a95 0x2f63356f 0x3a4d3d3f 0x3a4d86c3 0x2f628e7b 0x2f633271 0x2f5c7f49 0x1c67fb 0x2f62b9cd 0x3a4d9b3b 0x3a4d3d3f 0x3a4d66c3 0x2f81e681 0x2f81cf4d 0x2f787769 0x2f78754b 0x346f46d3 0x320e6891 0x72561 0x3a4e8ab7)
libc++abi.dylib: terminating with uncaught exception of type _NSCoreDataException
If I dont do a "save" then I see Cocoa Error 133000 on 4S devices. So there is definitely something I am messing up.
Appreciate any insights!
Your comment is along the correct lines, but not the correct solution. The problem is that you only save the main thread context and the change doesn't get pushed up to the parent (the persistent context). So, instead of calling if (![self.managedObjectContext save:&error]) { you should be calling if (![self.managedObjectContext saveToPersistentStore:&error]) {
I use core data in a background thread, when query data in a iteration using NSFetchRequest, it always get this error when executing [context executeFetchRequest: error:]:
2013-10-13 10:23:37.052 EExFab[157:217] CoreData: error: exception during newFetchedPKsForSourceID: statement is still active with userInfo of (null)
2013-10-13 10:23:37.056 EExFab[157:217] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'statement is still active'
*** First throw call stack:
(0x2fe76f53 0x3a24f6af 0x2fbc7999 0x2fbc71e5 0x2fbe0ef7 0x2fbd67ed 0x2fbcfa6f 0x2fbf9fcf 0x2fbf91f1 0x2fbf8e21 0x2fbf8a5b 0x2fbfb715 0x2fbf7d2b 0x2fbf7b73 0x307a59a1 0x307a5645 0x30791c5d 0x2fbefa03 0x2fbee3b3 0x9b9a1 0x2fbdc5a9 0x2fbdb4cf 0x2fca4ab3 0x2fca119b 0x2fbcf085 0x2fbceb33 0x2fbce3e5 0x2fbcc7e7 0xa9d69 0xa95ad 0xa4f0b 0xa9511 0x30859e27 0x3a876c1d 0x3a876b8f 0x3a874c90)
libc++abi.dylib: terminating with uncaught exception of type NSException
The code is like this:
#implementation EExFab{
NSString *filePath;
NSManagedObjectModel *model;
NSPersistentStoreCoordinator *coordinator;
NSManagedObjectContext *context;
NSFetchRequest *fetchRequest;
NSArray *fetchResult;
}
-(void)prepareCoreDataVariables{
NSError *error;
NSDictionary *options = #{NSMigratePersistentStoresAutomaticallyOption: #YES, NSInferMappingModelAutomaticallyOption: #YES};
if(!filePath)filePath=[[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"]stringByAppendingPathComponent:#"CDStoreOfEExFab.CDABStore"];
if(!model)model=[[NSManagedObjectModel alloc]initWithContentsOfURL:[[NSBundle mainBundle] URLForResource:#"EExFabModel" withExtension:#"momd"]];
if(!coordinator){
coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: model];
if(![coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:filePath isDirectory:NO] options:options error:&error]){
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
}
if(!context){
context=[[NSManagedObjectContext alloc] initWithConcurrencyType:NSConfinementConcurrencyType];
[context setPersistentStoreCoordinator: coordinator];
[context setUndoManager:nil];
}
if(!fetRequest)fetchRequest = [[NSFetchRequest alloc] init];
}
-(void)performBackgroundTask{ // invoker
[NSThread detachNewThreadSelector:#selector(onPerformBackgroundTask) toTarget:self withObject:nil];
}
-(void)onPerformBackgroundTask{
[self prepareCoreDataVariables];
// .... perform creation of Parsing some data into Core Data Storage using the variables
// .... NO error occurs during this period. ....
[self prepareCoreDataVariables];
for (id obj in someFetchedArray){
fetchRequest=[[NSFetchRequest alloc]init];
[fetchRequest setEntity:[NSEntityDescription entityForName:#"EExFabOBJ" inManagedObjectContext:context]];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"(timeOfCreation == %#)",obj.timeOfCreation]];
NSError *err=nil;
// ***************************CRASH*********************************************
fetchResult=[context executeFetchRequest:fetchRequest error:&err]; // <<<<<CRASH
// ***************************CRASH*********************************************
// .... other things ...
}
}
The app crashed at the first time of execution of the above code, there is no other thread or block using or used the local Core Data variables. Actually, these variables are initialized by the background thread itself.
Please pay attention on the block just above the crashed iteration, the Core Data Storage is initialized and parsed to be created in that block, they are in the same thread.
Please help, Thanks.
I'm trying to save a record in a table.
I read all the questions and answers in StackOverflow but I couldn't fix the problem.
When I try to save data, I get the error:
2013-08-31 22:25:37.321 OnTheRoadV2[26581:11603] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Trip''
*** First throw call stack:
(0x18e7012 0x1427e7e 0x743e7 0xba402 0x41db 0x143b705 0x372920 0x3728b8 0x433671 0x433bcf 0x432d38 0x3a233f 0x3a2552 0x3803aa 0x371cf8 0x2404df9 0x2404ad0 0x185cbf5 0x185c962 0x188dbb6 0x188cf44 0x188ce1b 0x24037e3 0x2403668 0x36f65c 0x29ed 0x2915)
libc++abi.dylib: terminate called throwing an exception
My code:
- (IBAction)start:(id)sender {
NSManagedObjectContext *context = [self managedObjectContext];
// Create a new managed object
NSManagedObject *newTrip = [NSEntityDescription insertNewObjectForEntityForName:#"Trip" inManagedObjectContext:context];
[newTrip setValue:self.name.text forKey:#"name"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
_status.text = #"Trip started!";
}
- (NSManagedObjectContext *)managedObjectContext {
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
[self managedObjectContext];
is returning nil, there isn't much more I can tell you from your posted code.
use magical record if you are new to core data.
its easy to integrate:
here is atutorial:
http://ablfx.com/blog/article/2