How Do I append CoreData Object with Swift?

Lucy Jeong

I'd like to add myplaceworks from server to coredata Here is my coredata object

private var user: [User]?
private var myPlaceOfWorks: [MyPlaceOfWorks]?
private var context = sharedManagedObjectContext()

and I tried this workplace of parameter is already made class.

this class controls array in json

func addInfo(workplace: [Sub_JsonModel_MyPlaceOfWorks], rtnvalue: String) ->
(User?, MyPlaceOfWorks?) {

    guard let newUser: User = 
NSEntityDescription.insertNewObjectForEntityForName("User",  
inManagedObjectContext: self.context) as? User else{
        return (nil, nil)

    }

    guard let newWorkPlace: MyPlaceOfWorks = 
NSEntityDescription.insertNewObjectForEntityForName("MyPlaceOfWorks", 
inManagedObjectContext: self.context) as? MyPlaceOfWorks else {
        return (nil, nil)
    }

    newUser.rtnvalue = rtnvalue

    for one in workplace {

        newWorkPlace.activeyn = one.ActiveYN
        newWorkPlace.basic = one.Basic
        newWorkPlace.beacon = one.Beacon
        newWorkPlace.cpiseq = one.CPISEQ
        newWorkPlace.cpmpoweq = one.CPMPOWSEQ
        newWorkPlace.companyname = one.CompanyName
        newWorkPlace.etime = one.ETime
        newWorkPlace.gps_latitude = one.GPS_latitude
        newWorkPlace.gps_longitude = one.GPS_longitude
        newWorkPlace.placename = one.PlaceName
        newWorkPlace.stime = one.STime
        newWorkPlace.wifi = one.Wifi
        self.myPlaceOfWorks?.append(newWorkPlace)
        print("newWorkPlace \(newWorkPlace)")
        print("myPlaceOfWorks \(myPlaceOfWorks)")
    }

    self.saveContext { 
        //action
        print("newUser:: \(newUser)")

    }
    return (newUser, newWorkPlace)
}

private func saveContext(completion: (() -> Void)?) {
    do {
        try self.context.save()
        if let handler = completion {
            NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                handler()
            })
        }
    } catch let error {
        print("can not save context \(error)")
    }
}

I can get rtnvalue but, I can't get myPlaceOfWorks array object! It is just nil How can I try this?

Mikhail Grebionkin

You've created only one object of MyPlaceOfWorks class and then rewriting properties of this object in the loop. Instead you need to create new instance on each loop iteration.

for one in workplace {
    if let newWorkPlace: MyPlaceOfWorks = NSEntityDescription.insertNewObjectForEntityForName("MyPlaceOfWorks", inManagedObjectContext: self.context) as? MyPlaceOfWorks {
        newWorkPlace.activeyn = one.ActiveYN
        newWorkPlace.basic = one.Basic
        newWorkPlace.beacon = one.Beacon
        newWorkPlace.cpiseq = one.CPISEQ
        newWorkPlace.cpmpoweq = one.CPMPOWSEQ
        newWorkPlace.companyname = one.CompanyName
        newWorkPlace.etime = one.ETime
        newWorkPlace.gps_latitude = one.GPS_latitude
        newWorkPlace.gps_longitude = one.GPS_longitude
        newWorkPlace.placename = one.PlaceName
        newWorkPlace.stime = one.STime
        newWorkPlace.wifi = one.Wifi
        self.myPlaceOfWorks?.append(newWorkPlace)
    }
}
self.saveContext { 
    //action
    print("newUser:: \(newUser)")

}

And as zcui93 has mentioned in comments you need to instantiate your myPlaceOfWorks variable:

private var myPlaceOfWorks = [MyPlaceOfWorks]()

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

In Swift, how do I avoid both optionals and nil object references?

How to append a tuple to an array object in Swift code?

How to do I initialise Swift array of object eg. CALayer

How do I pass a swift object to javascript (WKWebView / swift)

How to store custom object with CoreData in Swift?

How to Do a Lightweight CoreData Migration in Swift

In swift, how do I return an object of the same type that conforms to a protocol

How do I check if an object is a collection? (Swift)

How do i compare two dictionaries in swift and then append any similarities to a new dictionary?

How do I append a Python object attribute (list)

How do you append an array of keys to object?

How do I append more objects to a JSON object without overwriting it?

How do I append to a tuple?

How do I extract firebase functions to an object in Swift?

How do I append to a string?

If a property of my model object is an array of a custom object, how do I let users append objects to it?

Swift: How do I add data to a variable of an object in a list of objects

How do I append to a new object?

Swift - CoreData - DetailViewController - passing an object

In Swift, how do I check if an object is a collection of any type?

how can i get recent chat of a user from coreData swift

How do I encode a large Data object for a URL in Swift?

How can I append a string to an object property?

How do I append an element with an object as contents in it?

How do I safely unpack optionals (AlamoFire response object) in Swift

How do I convert JSON with variable variable names into swift object?

How do I append to array as an extension in swift

Wordpress rest API: How do I append all ACF of a Post Object?

How do I append to a file?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive