2

I'm looking to send and receive an NSManagedObject through the multipeer connectivity framework.

class MyObject: NSManagedObject {

@NSManaged var name: String
@NSManaged var children: NSSet

}

I've managed to send strings and dictionaries, but I need to send an NSManagedObject with an NSSet. Is this possible?

Here's what I've tried:

let data = NSKeyedArchiver.archivedDataWithRootObject(nsmanagedobject)

    if session.connectedPeers.count > 0 {

        var error: NSError?
        if !session.sendData(data,toPeers: session.connectedPeers, withMode: .Reliable, error: &error){

            println("SEND ERROR:")
            println(error)

        }

    } else {

        println("NO PEERS CONNECTED!")

    }

func session(session: MCSession!, didReceiveData data: NSData!, fromPeer peerID: MCPeerID!) {

    NSLog("%@", "didReceiveData: \(data.length) bytes")

    let nsmanagedobject = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! MyObject

}
AthleteInAction
  • 435
  • 4
  • 14

2 Answers2

2

The problem with sending an NSManagedObject to a different device is that it has been persisted to Core Data on the source device, but cannot simply be deserialized and inserted into the Persistent Store of the target.

I would suggest serializing the objects into NSDictionary, sending that data, and then implementing a find-or-create to correctly insert new Managed Objects on your target device.

ChrisH
  • 4,468
  • 2
  • 33
  • 42
1

No this is not possible. A NSManagedObject is more than just a storage for data it also has a state machine inside of it.

To send data like that you will need to convert it to a more primitive form, arrays, dictionaries, etc.

Marcus S. Zarra
  • 46,571
  • 9
  • 101
  • 182