Home > Back-end >  Failed to marshal the Objective-C object / Could not find an existing managed instance for this obje
Failed to marshal the Objective-C object / Could not find an existing managed instance for this obje

Time:02-06

I was occasionally getting the above error when saving a file to iCloud Drive and it was driving me crazy. So my eventual solution is below.

CodePudding user response:

Before saving a file to iCloud, I was removing any file of that name from iCloud:

if ( NSFileManager.DefaultManager.FileExists ( cloudFileUrl.Path ) )
    NSFileManager.DefaultManager.Remove ( cloudFileUrl, out cloudError );

I had neglected to make the file removal asynchronous, thus interfering with the later save. Here is my solution:

private static void RemoveiCloudFile ( NSUrl fileUrl )
// Removes file having the given url from iCloud Drive
{
    // Run asynchronously
    DispatchQueue.GetGlobalQueue ( DispatchQueuePriority.Default ).DispatchAsync ( () =>
    {
        DispatchQueue.MainQueue.DispatchAsync ( () =>
        {
            NSFileCoordinator fileCoordinator = new NSFileCoordinator ();
            NSError error;
            bool success = false;

            fileCoordinator.CoordinateWrite ( fileUrl , NSFileCoordinatorWritingOptions.ForDeleting,
                                                out error, removalUrl =>
                                                {
                                                    NSFileManager fileManager = new NSFileManager ();
                                                    success = fileManager.Remove ( removalUrl, out error );
                                                });
            if ( ! success )
            {
                // Your code here   
            }
        });
    });
}
  •  Tags:  
  • Related