Can't establish a relationship between objects in different contexts when using a background context

Multi tool use
Multi tool use












0















I'm trying to insert an NSManagedObject through a background context and I'm getting this error:



Illegal attempt to establish a relationship 'location' between objects in different contexts (source = <Image: 0x600002f81b80> (entity: Image; id: 0x600000f44fe0 <x-coredata:///Image/t8C3934D6-DCD7-4A7B-A69C-9C18334F7A942> ; data: {
image = <ffd8ffe0 00104a46 49460001 01000048 00480000 ffe10058 45786966 00004d4d 002a0000 00080002 01120003 00000001 0001>;
location = nil;
}) , destination = <Location: 0x600002fb3020> (entity: Location; id: 0xd78dad45136e9365 <x-coredata://9CA497CF-69A8-44ED-8741-C75AF480446E/Location/p2> ; data: {
images = "<relationship fault: 0x600000f44480 'images'>";
location = "29.977646364835238,31.32489065578125";
}))


I know this question was asked several times before, I've checked some of the answers but I really couldn't know what my code lacks. Here is my code:



func saveImagesToDb () {

//Store the image in the DB along with its location on the background thread
dataController.backgroundContext.perform {
let imageOnMainContext = Image (context: self.dataController.viewContext)
let imageManagedObjectId = imageOnMainContext.objectID
let imageOnBackgroundContext = self.dataController.backgroundContext.object(with: imageManagedObjectId) as! Image

for downloadedImage in self.downloadedImages {

let imageData = NSData (data: downloadedImage.jpegData(compressionQuality: 0.5)!)
imageOnBackgroundContext.image = imageData as Data
imageOnBackgroundContext.location = self.imagesLocation


try? self.dataController.backgroundContext.save ()
}
}


}


I just have two entities, Location and Image. The Location has an attribute called location, and Image has an attribute called image. There is a one-to-many relationship between them (one location can have many images).



I'm aware that every context preserves its own copy of NSManagedObjects. That's why, in the code I first got an Image based on the view context, got its id, then used that id to get an Image object on the background context.



What am I doing wrong?



I'm new to Core Data so I'll appreciate any help that can explain to me what's happening here and how I can solve it.



Update: The problem was with imagesLocation which was built on the view context, so I just created a corresponding object from it using its ID on the background context. After that, the problem was solved, but I also had a problem with Image object and relationship as in my question here. I could solve that and I posted the answer, you can check it.










share|improve this question




















  • 1





    The problem probably lies in your line which sets the location on imageOnBackgroundContext to self.imagesLocation. That imagesLocation variable probably holds an NSManagedObject on a context that is not your backgroundContext.

    – FJ de Brienne
    Dec 31 '18 at 13:39











  • @FJdeBrienne Yes you're right, imagesLocation has a value of a Location that's created on the main thread. I made a Location object on the background context using the ID as I did with the Image object and it worked but I got another error about which may post another question. Can you please post your comment as an answer so I can accept it and update my question? Thank you for the help

    – Dania
    Dec 31 '18 at 14:47













  • thanks, I wrote the answer.

    – FJ de Brienne
    Dec 31 '18 at 15:19
















0















I'm trying to insert an NSManagedObject through a background context and I'm getting this error:



Illegal attempt to establish a relationship 'location' between objects in different contexts (source = <Image: 0x600002f81b80> (entity: Image; id: 0x600000f44fe0 <x-coredata:///Image/t8C3934D6-DCD7-4A7B-A69C-9C18334F7A942> ; data: {
image = <ffd8ffe0 00104a46 49460001 01000048 00480000 ffe10058 45786966 00004d4d 002a0000 00080002 01120003 00000001 0001>;
location = nil;
}) , destination = <Location: 0x600002fb3020> (entity: Location; id: 0xd78dad45136e9365 <x-coredata://9CA497CF-69A8-44ED-8741-C75AF480446E/Location/p2> ; data: {
images = "<relationship fault: 0x600000f44480 'images'>";
location = "29.977646364835238,31.32489065578125";
}))


I know this question was asked several times before, I've checked some of the answers but I really couldn't know what my code lacks. Here is my code:



func saveImagesToDb () {

//Store the image in the DB along with its location on the background thread
dataController.backgroundContext.perform {
let imageOnMainContext = Image (context: self.dataController.viewContext)
let imageManagedObjectId = imageOnMainContext.objectID
let imageOnBackgroundContext = self.dataController.backgroundContext.object(with: imageManagedObjectId) as! Image

for downloadedImage in self.downloadedImages {

let imageData = NSData (data: downloadedImage.jpegData(compressionQuality: 0.5)!)
imageOnBackgroundContext.image = imageData as Data
imageOnBackgroundContext.location = self.imagesLocation


try? self.dataController.backgroundContext.save ()
}
}


}


I just have two entities, Location and Image. The Location has an attribute called location, and Image has an attribute called image. There is a one-to-many relationship between them (one location can have many images).



I'm aware that every context preserves its own copy of NSManagedObjects. That's why, in the code I first got an Image based on the view context, got its id, then used that id to get an Image object on the background context.



What am I doing wrong?



I'm new to Core Data so I'll appreciate any help that can explain to me what's happening here and how I can solve it.



Update: The problem was with imagesLocation which was built on the view context, so I just created a corresponding object from it using its ID on the background context. After that, the problem was solved, but I also had a problem with Image object and relationship as in my question here. I could solve that and I posted the answer, you can check it.










share|improve this question




















  • 1





    The problem probably lies in your line which sets the location on imageOnBackgroundContext to self.imagesLocation. That imagesLocation variable probably holds an NSManagedObject on a context that is not your backgroundContext.

    – FJ de Brienne
    Dec 31 '18 at 13:39











  • @FJdeBrienne Yes you're right, imagesLocation has a value of a Location that's created on the main thread. I made a Location object on the background context using the ID as I did with the Image object and it worked but I got another error about which may post another question. Can you please post your comment as an answer so I can accept it and update my question? Thank you for the help

    – Dania
    Dec 31 '18 at 14:47













  • thanks, I wrote the answer.

    – FJ de Brienne
    Dec 31 '18 at 15:19














0












0








0








I'm trying to insert an NSManagedObject through a background context and I'm getting this error:



Illegal attempt to establish a relationship 'location' between objects in different contexts (source = <Image: 0x600002f81b80> (entity: Image; id: 0x600000f44fe0 <x-coredata:///Image/t8C3934D6-DCD7-4A7B-A69C-9C18334F7A942> ; data: {
image = <ffd8ffe0 00104a46 49460001 01000048 00480000 ffe10058 45786966 00004d4d 002a0000 00080002 01120003 00000001 0001>;
location = nil;
}) , destination = <Location: 0x600002fb3020> (entity: Location; id: 0xd78dad45136e9365 <x-coredata://9CA497CF-69A8-44ED-8741-C75AF480446E/Location/p2> ; data: {
images = "<relationship fault: 0x600000f44480 'images'>";
location = "29.977646364835238,31.32489065578125";
}))


I know this question was asked several times before, I've checked some of the answers but I really couldn't know what my code lacks. Here is my code:



func saveImagesToDb () {

//Store the image in the DB along with its location on the background thread
dataController.backgroundContext.perform {
let imageOnMainContext = Image (context: self.dataController.viewContext)
let imageManagedObjectId = imageOnMainContext.objectID
let imageOnBackgroundContext = self.dataController.backgroundContext.object(with: imageManagedObjectId) as! Image

for downloadedImage in self.downloadedImages {

let imageData = NSData (data: downloadedImage.jpegData(compressionQuality: 0.5)!)
imageOnBackgroundContext.image = imageData as Data
imageOnBackgroundContext.location = self.imagesLocation


try? self.dataController.backgroundContext.save ()
}
}


}


I just have two entities, Location and Image. The Location has an attribute called location, and Image has an attribute called image. There is a one-to-many relationship between them (one location can have many images).



I'm aware that every context preserves its own copy of NSManagedObjects. That's why, in the code I first got an Image based on the view context, got its id, then used that id to get an Image object on the background context.



What am I doing wrong?



I'm new to Core Data so I'll appreciate any help that can explain to me what's happening here and how I can solve it.



Update: The problem was with imagesLocation which was built on the view context, so I just created a corresponding object from it using its ID on the background context. After that, the problem was solved, but I also had a problem with Image object and relationship as in my question here. I could solve that and I posted the answer, you can check it.










share|improve this question
















I'm trying to insert an NSManagedObject through a background context and I'm getting this error:



Illegal attempt to establish a relationship 'location' between objects in different contexts (source = <Image: 0x600002f81b80> (entity: Image; id: 0x600000f44fe0 <x-coredata:///Image/t8C3934D6-DCD7-4A7B-A69C-9C18334F7A942> ; data: {
image = <ffd8ffe0 00104a46 49460001 01000048 00480000 ffe10058 45786966 00004d4d 002a0000 00080002 01120003 00000001 0001>;
location = nil;
}) , destination = <Location: 0x600002fb3020> (entity: Location; id: 0xd78dad45136e9365 <x-coredata://9CA497CF-69A8-44ED-8741-C75AF480446E/Location/p2> ; data: {
images = "<relationship fault: 0x600000f44480 'images'>";
location = "29.977646364835238,31.32489065578125";
}))


I know this question was asked several times before, I've checked some of the answers but I really couldn't know what my code lacks. Here is my code:



func saveImagesToDb () {

//Store the image in the DB along with its location on the background thread
dataController.backgroundContext.perform {
let imageOnMainContext = Image (context: self.dataController.viewContext)
let imageManagedObjectId = imageOnMainContext.objectID
let imageOnBackgroundContext = self.dataController.backgroundContext.object(with: imageManagedObjectId) as! Image

for downloadedImage in self.downloadedImages {

let imageData = NSData (data: downloadedImage.jpegData(compressionQuality: 0.5)!)
imageOnBackgroundContext.image = imageData as Data
imageOnBackgroundContext.location = self.imagesLocation


try? self.dataController.backgroundContext.save ()
}
}


}


I just have two entities, Location and Image. The Location has an attribute called location, and Image has an attribute called image. There is a one-to-many relationship between them (one location can have many images).



I'm aware that every context preserves its own copy of NSManagedObjects. That's why, in the code I first got an Image based on the view context, got its id, then used that id to get an Image object on the background context.



What am I doing wrong?



I'm new to Core Data so I'll appreciate any help that can explain to me what's happening here and how I can solve it.



Update: The problem was with imagesLocation which was built on the view context, so I just created a corresponding object from it using its ID on the background context. After that, the problem was solved, but I also had a problem with Image object and relationship as in my question here. I could solve that and I posted the answer, you can check it.







ios swift xcode core-data






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 3 at 19:37







Dania

















asked Dec 31 '18 at 12:12









DaniaDania

79921538




79921538








  • 1





    The problem probably lies in your line which sets the location on imageOnBackgroundContext to self.imagesLocation. That imagesLocation variable probably holds an NSManagedObject on a context that is not your backgroundContext.

    – FJ de Brienne
    Dec 31 '18 at 13:39











  • @FJdeBrienne Yes you're right, imagesLocation has a value of a Location that's created on the main thread. I made a Location object on the background context using the ID as I did with the Image object and it worked but I got another error about which may post another question. Can you please post your comment as an answer so I can accept it and update my question? Thank you for the help

    – Dania
    Dec 31 '18 at 14:47













  • thanks, I wrote the answer.

    – FJ de Brienne
    Dec 31 '18 at 15:19














  • 1





    The problem probably lies in your line which sets the location on imageOnBackgroundContext to self.imagesLocation. That imagesLocation variable probably holds an NSManagedObject on a context that is not your backgroundContext.

    – FJ de Brienne
    Dec 31 '18 at 13:39











  • @FJdeBrienne Yes you're right, imagesLocation has a value of a Location that's created on the main thread. I made a Location object on the background context using the ID as I did with the Image object and it worked but I got another error about which may post another question. Can you please post your comment as an answer so I can accept it and update my question? Thank you for the help

    – Dania
    Dec 31 '18 at 14:47













  • thanks, I wrote the answer.

    – FJ de Brienne
    Dec 31 '18 at 15:19








1




1





The problem probably lies in your line which sets the location on imageOnBackgroundContext to self.imagesLocation. That imagesLocation variable probably holds an NSManagedObject on a context that is not your backgroundContext.

– FJ de Brienne
Dec 31 '18 at 13:39





The problem probably lies in your line which sets the location on imageOnBackgroundContext to self.imagesLocation. That imagesLocation variable probably holds an NSManagedObject on a context that is not your backgroundContext.

– FJ de Brienne
Dec 31 '18 at 13:39













@FJdeBrienne Yes you're right, imagesLocation has a value of a Location that's created on the main thread. I made a Location object on the background context using the ID as I did with the Image object and it worked but I got another error about which may post another question. Can you please post your comment as an answer so I can accept it and update my question? Thank you for the help

– Dania
Dec 31 '18 at 14:47







@FJdeBrienne Yes you're right, imagesLocation has a value of a Location that's created on the main thread. I made a Location object on the background context using the ID as I did with the Image object and it worked but I got another error about which may post another question. Can you please post your comment as an answer so I can accept it and update my question? Thank you for the help

– Dania
Dec 31 '18 at 14:47















thanks, I wrote the answer.

– FJ de Brienne
Dec 31 '18 at 15:19





thanks, I wrote the answer.

– FJ de Brienne
Dec 31 '18 at 15:19












1 Answer
1






active

oldest

votes


















1














It seems as though self.imagesLocation is an NSManagedObject created on a foreign thread and, as such, cannot be assigned to the imageOnBackgroundContext.



You should fetch the object pointed to by self.imagesLocation in your backgroundContext using its NSManagedObjectID and assign that fetched object to your imageOnBackgroundContext






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53987377%2fcant-establish-a-relationship-between-objects-in-different-contexts-when-using%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    It seems as though self.imagesLocation is an NSManagedObject created on a foreign thread and, as such, cannot be assigned to the imageOnBackgroundContext.



    You should fetch the object pointed to by self.imagesLocation in your backgroundContext using its NSManagedObjectID and assign that fetched object to your imageOnBackgroundContext






    share|improve this answer




























      1














      It seems as though self.imagesLocation is an NSManagedObject created on a foreign thread and, as such, cannot be assigned to the imageOnBackgroundContext.



      You should fetch the object pointed to by self.imagesLocation in your backgroundContext using its NSManagedObjectID and assign that fetched object to your imageOnBackgroundContext






      share|improve this answer


























        1












        1








        1







        It seems as though self.imagesLocation is an NSManagedObject created on a foreign thread and, as such, cannot be assigned to the imageOnBackgroundContext.



        You should fetch the object pointed to by self.imagesLocation in your backgroundContext using its NSManagedObjectID and assign that fetched object to your imageOnBackgroundContext






        share|improve this answer













        It seems as though self.imagesLocation is an NSManagedObject created on a foreign thread and, as such, cannot be assigned to the imageOnBackgroundContext.



        You should fetch the object pointed to by self.imagesLocation in your backgroundContext using its NSManagedObjectID and assign that fetched object to your imageOnBackgroundContext







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 31 '18 at 15:19









        FJ de BrienneFJ de Brienne

        14610




        14610
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53987377%2fcant-establish-a-relationship-between-objects-in-different-contexts-when-using%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            qG2 IcWuTYQZnlVqoxMO,x0fzlgBHqgN,IJMY8cN6,3B,7hLTT4cBmp8Fi8l9ZOx,Q7
            DpL2H7J,hckCkrbXbIrohMtM,2p8PFKkTIJZMz ixC4XcH,xMdUi56NkzOyCcwelGnjiQj,A7r1

            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas