无法编组 Objective-C 对象/找不到此对象的现有托管实例 - 在 Xamarin iOS 中保存到 iCloud Drive 时

Failed to marshal the Objective-C object / Could not find an existing managed instance for this object - when saving to iCloud Drive in Xamarin iOS

我在将文件保存到 iCloud Drive 时偶尔会遇到上述错误,这让我抓狂。所以我最终的解决方案如下。

在将文件保存到 iCloud 之前,我从 iCloud 中删除了任何同名文件:

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

我忘记了异步删除文件,因此干扰了以后的保存。这是我的解决方案:

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   
            }
        });
    });
}