NSCoding data not saved when returning to the app?

NSCoding data not saved when returning to the app?

By : Knyazushka
Date : November 17 2020, 01:00 AM
like below fixes the issue I don't understand why previousArrays returns (null), I would like to save a class containing a bezier path and its color. , I had to use this : if ( previousArray == nil ) ...
code :
NSMutableArray *previousArray = [[NSKeyedUnarchiver unarchiveObjectWithData:previousData] mutableCopy];
if ( previousArray == nil ) previousArray = [[NSMutableArray alloc] init];

Share : facebook icon twitter icon
NSCoding NSKeyedUnarchiver unarchiveObjectWithFile: returning null

NSCoding NSKeyedUnarchiver unarchiveObjectWithFile: returning null

By : Source Code
Date : March 29 2020, 07:55 AM
wish helps you The path where you save and load your reminder is wrong. Maybe replace to this
code :
NSString *reminderEventIDsPathString = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"ReminderIDs.archive"];
NSCoding gamedata not saved swift

NSCoding gamedata not saved swift

By : user3535517
Date : March 29 2020, 07:55 AM
this one helps. Like Jozsef said, I forgot to decode the data. However I need to decode each of the individual variables and then copy it over to the GameData for it to work.
code :
class GameData : NSObject, NSCoding {

/// Data to save

var variableC : Int! = 3

/// Create of shared instance

class var sharedInstance: GameData {

    struct Static {
        static var instance: GameData?
        static var token: dispatch_once_t = 0

    dispatch_once(&Static.token) {
        var gamedata = GameData()
        if let savedData = GameData.loadGame() {
            gamedata.variableC = savedData.variableC
        Static.instance = gamedata

    return Static.instance!

override init() {

required init(coder: NSCoder) {
    self.variableC = coder.decodeObjectForKey("variableC") as? Int


func encodeWithCoder(coder: NSCoder) {
    coder.encodeObject(GameData.sharedInstance.variableC, forKey: "variableC")

class func loadGame() -> GameData? {
    // load existing high scores or set up an empty array
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0] as! String
    let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist")
    let fileManager = NSFileManager.defaultManager()

    // check if file exists
    if !fileManager.fileExistsAtPath(path) {
        // create an empty file if it doesn't exist
        println("File doesn't exist")
        if let bundle = NSBundle.mainBundle().pathForResource("DefaultFile", ofType: "plist") {
            fileManager.copyItemAtPath(bundle, toPath: path, error:nil)

    if let rawData = NSData(contentsOfFile: path) {
        // do we get serialized data back from the attempted path?
        // if so, unarchive it into an AnyObject, and then convert to an array of HighScores, if possible
        if let data = NSKeyedUnarchiver.unarchiveObjectWithData(rawData) as? GameData {
            println("We loaded the data!")
            return data
    return nil

func save() {
    // find the save directory our app has permission to use, and save the serialized version of self.scores - the HighScores array.
    let saveData = NSKeyedArchiver.archivedDataWithRootObject(GameData.sharedInstance);
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray;
    let documentsDirectory = paths.objectAtIndex(0)as! NSString;
    let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist");

    saveData.writeToFile(path, atomically: true);
PINCache objectForKey returning NSCoding and can't casting it

PINCache objectForKey returning NSCoding and can't casting it

By : Dronic X
Date : March 29 2020, 07:55 AM
wish helps you It looks like PINCache is not defining the return types of the synchronous objectForKey: methods as __nullable. Without that Swift doesn't know that the return type is optional.
I submitted a PR, which has already been accepted, that should fix the problem. You should now be able to do something like:
code :
let trucksCached: AnyObject? = PINDiskCache.sharedCache().objectForKey("truck_key")
if let _truck = trucksCached as? Truck {
Swift NSKeyedArchiver: Do custom members of an NSCoding-conformant class need to conform to NSCoding as well?

Swift NSKeyedArchiver: Do custom members of an NSCoding-conformant class need to conform to NSCoding as well?

By : paulhewett
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , The answer is "yes". Custom object members must also conform to NSCoding.
Why is NSCoding unable to decode an object once saved properly?

Why is NSCoding unable to decode an object once saved properly?

By : user3585584
Date : March 29 2020, 07:55 AM
With these it helps Here is the full class I am saving in core data as a transformable. , Key value coding-compliant properties must be marked as @objc dynamic
code :
public class Item: NSObject, NSCoding {
    dynamic public var imageData: Data
    dynamic public var title: String
    dynamic public var keywords: [String]
    dynamic public var date: Date

public required convenience init?(coder aDecoder: NSCoder) {
        imageData: (aDecoder.decodeObject(forKey: "imageData") as? Data) ?? Data(),
        title: (aDecoder.decodeObject(forKey: "title") as? String) ?? "",
        date: Date(timeIntervalSince1970: aDecoder.decodeDouble(forKey: "date")),
        keywords: aDecoder.decodeObject(forKey: "keywords") as? [String] ?? [])
Related Posts Related Posts :
  • CordovaError: Promise rejected with non-error: Error code 65
  • How to append NSMutable strings into a UILabel
  • CustomCell label value does not change
  • Display ad in iAd Bannerview iAd Network
  • Warning: "Could not get traitsetID for iPhone11,6" (Assets.xcassets)
  • Changing root view controller after iOS app has loaded.
  • SocketRocket and iOS certificate pinning
  • Draggable UIButton Snap To a Circle Path
  • Running FireBase in the background
  • resizing UIPopoverController to fit UITableController
  • UICollectionView Exception Crash
  • targeting iOS5 - will it work on iOS6 also?
  • FBLoginView get email
  • Scale UIImages height to UIImageView height
  • Creating a custom progress indicator in ios
  • NSRunLoop API difference
  • Is it possible to inject custom settings into my iOS application "Notifications" settings dialog?
  • UIAlertview not accepting string as message
  • Axis change of stackView giving layout error
  • How to use AVAssetResourceLoader?
  • How to write block definition using properties?
  • iOS connect/reconnect to Bluetooth device when using external-accessory and MFi
  • Saving XMPP Multi User chat messages through XMPP MessageArchiving in iOS
  • Deciding iOS version: pros and cons
  • iOS: Resigned app cannot access keychain through security API
  • How can I set To and Subject fields in an E-Mail being sent by UIDocumentInteractionController?
  • Updating uilabel in view controller underneath another
  • Maximum time Intervel for NSTimer
  • Delete Core Data Entry from Table View Controller
  • How to unload UIViewcontroller from memory?
  • Compressing UIImage as Far as Possible?
  • Optimizing workflow to update internally owned cocoapods dependencies?
  • Formatting an NSDate with Abbreviated Month/Day Names
  • I'm creating a quiz game with 4 answers and I want to add score
  • Tap Gesture to Hide Navigation Bar, Tab Bar, and Status Bar
  • FBSessionStateClosedLoginFailed when I am logged in through Settings
  • CGRect positioning according to center point
  • iOS: Update table view datasource with animations without core data
  • iOS : Where to start for AliPay integration?
  • Routing App Coverage File missing but not needed?
  • Drawing on a zoomable view
  • Append NSStrings and NSNumber to NSMutableArrays and make NSMutable dictionary
  • Terminating app due to uncaught exception 'NSRangeException' when calling dequeueReusableCellWithReuseIdentifier:forInde
  • Collision without physics (Cocos2D + Box2D iOS)
  • Creating a percentage based iOS layout
  • Update tableView row from AppDelegate Swift 4
  • Assigning return value of a class method to a variable error
  • how to display circular progress in delphi ios apps?
  • I can't figure how to fix this Expected identifier or '('
  • How to Test APIs in Swift 4?
  • Link error /Build/Products/Debug-iphonesimulator file not found
  • working with a very large JSON object in iOS
  • Turn off part of the iPhone Screen
  • Phonegap 3.0 app with facebook login using xCode
  • How to add interstitial admob ads to my ios project
  • adding tapku calendar to ios app
  • Add an alertcontroller in a global swift file?
  • Take square image with Cordova (Phonegap) Camera API?
  • Amazon S3 policy allowing only upload not overwrite
  • How to change the UILabel content by tapping?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org