Can't save Bool in Swift










0















I'm new to Swift (background in C++) and I'm trying to do a very simple thing: save a Bool. It works perfectly if I convert the bool to a string that is either "A" or "B" and then convert back but if I save the bool directly with encode and aDecoder the Bool comes back nil every time. Can't find anything about it on the internet.



As you can see below I simply substitute a string for a Bool and it works.



func boolwontsave(aBool:Bool) -> String 
if aBool
return "A"

return "B"


func encode(with aCoder: NSCoder)

aCoder.encode(name, forKey: PropertyKey.name)
aCoder.encode(number, forKey: PropertyKey.number)
aCoder.encode(boolwontsave(aBool: ispresent), forKey: PropertyKey.present)



required convenience init?(coder aDecoder: NSCoder)

// The name is required. If we cannot decode a name string, the initializer should fail.
guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else
os_log("Unable to decode the name for a player object.", log: OSLog.default, type: .debug)
return nil


let number = aDecoder.decodeObject(forKey: PropertyKey.number) as? String

guard let localpresent = aDecoder.decodeObject(forKey: PropertyKey.present) as? String else
print("got the nil")
os_log("Unable to decode the ispresent for a player object.", log: OSLog.default, type: .debug)
return nil



// Must call designated initializer.
self.init(name:name, number:number, present: localpresent == "A")




Aren't Bools supposed to save? This seems inelegant.










share|improve this question
























  • What do you mean by saying "save a bool". Also please provide a code where you're trying to retrieve your bool and it return nil.

    – inokey
    Nov 15 '18 at 15:17











  • A bigger question is why you are using NSCoding and NSCoder in Swift. Is there a reason you are not using the Swift Codable features instead?

    – rmaddy
    Nov 15 '18 at 16:26















0















I'm new to Swift (background in C++) and I'm trying to do a very simple thing: save a Bool. It works perfectly if I convert the bool to a string that is either "A" or "B" and then convert back but if I save the bool directly with encode and aDecoder the Bool comes back nil every time. Can't find anything about it on the internet.



As you can see below I simply substitute a string for a Bool and it works.



func boolwontsave(aBool:Bool) -> String 
if aBool
return "A"

return "B"


func encode(with aCoder: NSCoder)

aCoder.encode(name, forKey: PropertyKey.name)
aCoder.encode(number, forKey: PropertyKey.number)
aCoder.encode(boolwontsave(aBool: ispresent), forKey: PropertyKey.present)



required convenience init?(coder aDecoder: NSCoder)

// The name is required. If we cannot decode a name string, the initializer should fail.
guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else
os_log("Unable to decode the name for a player object.", log: OSLog.default, type: .debug)
return nil


let number = aDecoder.decodeObject(forKey: PropertyKey.number) as? String

guard let localpresent = aDecoder.decodeObject(forKey: PropertyKey.present) as? String else
print("got the nil")
os_log("Unable to decode the ispresent for a player object.", log: OSLog.default, type: .debug)
return nil



// Must call designated initializer.
self.init(name:name, number:number, present: localpresent == "A")




Aren't Bools supposed to save? This seems inelegant.










share|improve this question
























  • What do you mean by saying "save a bool". Also please provide a code where you're trying to retrieve your bool and it return nil.

    – inokey
    Nov 15 '18 at 15:17











  • A bigger question is why you are using NSCoding and NSCoder in Swift. Is there a reason you are not using the Swift Codable features instead?

    – rmaddy
    Nov 15 '18 at 16:26













0












0








0








I'm new to Swift (background in C++) and I'm trying to do a very simple thing: save a Bool. It works perfectly if I convert the bool to a string that is either "A" or "B" and then convert back but if I save the bool directly with encode and aDecoder the Bool comes back nil every time. Can't find anything about it on the internet.



As you can see below I simply substitute a string for a Bool and it works.



func boolwontsave(aBool:Bool) -> String 
if aBool
return "A"

return "B"


func encode(with aCoder: NSCoder)

aCoder.encode(name, forKey: PropertyKey.name)
aCoder.encode(number, forKey: PropertyKey.number)
aCoder.encode(boolwontsave(aBool: ispresent), forKey: PropertyKey.present)



required convenience init?(coder aDecoder: NSCoder)

// The name is required. If we cannot decode a name string, the initializer should fail.
guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else
os_log("Unable to decode the name for a player object.", log: OSLog.default, type: .debug)
return nil


let number = aDecoder.decodeObject(forKey: PropertyKey.number) as? String

guard let localpresent = aDecoder.decodeObject(forKey: PropertyKey.present) as? String else
print("got the nil")
os_log("Unable to decode the ispresent for a player object.", log: OSLog.default, type: .debug)
return nil



// Must call designated initializer.
self.init(name:name, number:number, present: localpresent == "A")




Aren't Bools supposed to save? This seems inelegant.










share|improve this question
















I'm new to Swift (background in C++) and I'm trying to do a very simple thing: save a Bool. It works perfectly if I convert the bool to a string that is either "A" or "B" and then convert back but if I save the bool directly with encode and aDecoder the Bool comes back nil every time. Can't find anything about it on the internet.



As you can see below I simply substitute a string for a Bool and it works.



func boolwontsave(aBool:Bool) -> String 
if aBool
return "A"

return "B"


func encode(with aCoder: NSCoder)

aCoder.encode(name, forKey: PropertyKey.name)
aCoder.encode(number, forKey: PropertyKey.number)
aCoder.encode(boolwontsave(aBool: ispresent), forKey: PropertyKey.present)



required convenience init?(coder aDecoder: NSCoder)

// The name is required. If we cannot decode a name string, the initializer should fail.
guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else
os_log("Unable to decode the name for a player object.", log: OSLog.default, type: .debug)
return nil


let number = aDecoder.decodeObject(forKey: PropertyKey.number) as? String

guard let localpresent = aDecoder.decodeObject(forKey: PropertyKey.present) as? String else
print("got the nil")
os_log("Unable to decode the ispresent for a player object.", log: OSLog.default, type: .debug)
return nil



// Must call designated initializer.
self.init(name:name, number:number, present: localpresent == "A")




Aren't Bools supposed to save? This seems inelegant.







swift nscoding






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 16:24









rmaddy

245k27324388




245k27324388










asked Nov 15 '18 at 15:09









Sam HawksworthSam Hawksworth

1




1












  • What do you mean by saying "save a bool". Also please provide a code where you're trying to retrieve your bool and it return nil.

    – inokey
    Nov 15 '18 at 15:17











  • A bigger question is why you are using NSCoding and NSCoder in Swift. Is there a reason you are not using the Swift Codable features instead?

    – rmaddy
    Nov 15 '18 at 16:26

















  • What do you mean by saying "save a bool". Also please provide a code where you're trying to retrieve your bool and it return nil.

    – inokey
    Nov 15 '18 at 15:17











  • A bigger question is why you are using NSCoding and NSCoder in Swift. Is there a reason you are not using the Swift Codable features instead?

    – rmaddy
    Nov 15 '18 at 16:26
















What do you mean by saying "save a bool". Also please provide a code where you're trying to retrieve your bool and it return nil.

– inokey
Nov 15 '18 at 15:17





What do you mean by saying "save a bool". Also please provide a code where you're trying to retrieve your bool and it return nil.

– inokey
Nov 15 '18 at 15:17













A bigger question is why you are using NSCoding and NSCoder in Swift. Is there a reason you are not using the Swift Codable features instead?

– rmaddy
Nov 15 '18 at 16:26





A bigger question is why you are using NSCoding and NSCoder in Swift. Is there a reason you are not using the Swift Codable features instead?

– rmaddy
Nov 15 '18 at 16:26












2 Answers
2






active

oldest

votes


















1














It's very easy to save a Bool if you are using the proper API.



In terms of NSCoding a Bool is not an object, there is a decodeBool(forKey method.



required convenience init?(coder aDecoder: NSCoder) 

// The name is required. If we cannot decode a name string, the initializer should fail.
guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else
os_log("Unable to decode the name for a player object.", log: OSLog.default, type: .debug)
return nil


let number = aDecoder.decodeObject(forKey: PropertyKey.number) as? String
let localpresent = aDecoder.decodeBool(forKey: PropertyKey.present)

// Must call designated initializer.
self.init(name:name, number:number, present: localpresent)



func encode(with aCoder: NSCoder)
aCoder.encode(name, forKey: PropertyKey.name)
aCoder.encode(number, forKey: PropertyKey.number)
aCoder.encode(ispresent, forKey: PropertyKey.present)



In Swift 4+ I'd prefer the native Codable protocol over constrained NSCoding.




  • NSCoding requires an class inherited from NSObject.


  • Codable can be used for any struct, class and enum which conforms to the protocol.





share|improve this answer























  • Thanks for all the quick answers. I'll convert to using Codable, which I think will also solve my other challenge around saving nested arrays. Thanks again everyone!

    – Sam Hawksworth
    Nov 15 '18 at 18:45


















0














Use decodeBool(forKey key: String) instead of decodeObject(forKey: String)



DecodeBool decodes and returns a boolean value that was previously encoded with encode(_:forKey:) and associated with the string key.



aCoder.encode(true, forKey: PropertyKey.present)
aCoder.decodeBool(forKey: PropertyKey.present)





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%2f53322413%2fcant-save-bool-in-swift%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    It's very easy to save a Bool if you are using the proper API.



    In terms of NSCoding a Bool is not an object, there is a decodeBool(forKey method.



    required convenience init?(coder aDecoder: NSCoder) 

    // The name is required. If we cannot decode a name string, the initializer should fail.
    guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else
    os_log("Unable to decode the name for a player object.", log: OSLog.default, type: .debug)
    return nil


    let number = aDecoder.decodeObject(forKey: PropertyKey.number) as? String
    let localpresent = aDecoder.decodeBool(forKey: PropertyKey.present)

    // Must call designated initializer.
    self.init(name:name, number:number, present: localpresent)



    func encode(with aCoder: NSCoder)
    aCoder.encode(name, forKey: PropertyKey.name)
    aCoder.encode(number, forKey: PropertyKey.number)
    aCoder.encode(ispresent, forKey: PropertyKey.present)



    In Swift 4+ I'd prefer the native Codable protocol over constrained NSCoding.




    • NSCoding requires an class inherited from NSObject.


    • Codable can be used for any struct, class and enum which conforms to the protocol.





    share|improve this answer























    • Thanks for all the quick answers. I'll convert to using Codable, which I think will also solve my other challenge around saving nested arrays. Thanks again everyone!

      – Sam Hawksworth
      Nov 15 '18 at 18:45















    1














    It's very easy to save a Bool if you are using the proper API.



    In terms of NSCoding a Bool is not an object, there is a decodeBool(forKey method.



    required convenience init?(coder aDecoder: NSCoder) 

    // The name is required. If we cannot decode a name string, the initializer should fail.
    guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else
    os_log("Unable to decode the name for a player object.", log: OSLog.default, type: .debug)
    return nil


    let number = aDecoder.decodeObject(forKey: PropertyKey.number) as? String
    let localpresent = aDecoder.decodeBool(forKey: PropertyKey.present)

    // Must call designated initializer.
    self.init(name:name, number:number, present: localpresent)



    func encode(with aCoder: NSCoder)
    aCoder.encode(name, forKey: PropertyKey.name)
    aCoder.encode(number, forKey: PropertyKey.number)
    aCoder.encode(ispresent, forKey: PropertyKey.present)



    In Swift 4+ I'd prefer the native Codable protocol over constrained NSCoding.




    • NSCoding requires an class inherited from NSObject.


    • Codable can be used for any struct, class and enum which conforms to the protocol.





    share|improve this answer























    • Thanks for all the quick answers. I'll convert to using Codable, which I think will also solve my other challenge around saving nested arrays. Thanks again everyone!

      – Sam Hawksworth
      Nov 15 '18 at 18:45













    1












    1








    1







    It's very easy to save a Bool if you are using the proper API.



    In terms of NSCoding a Bool is not an object, there is a decodeBool(forKey method.



    required convenience init?(coder aDecoder: NSCoder) 

    // The name is required. If we cannot decode a name string, the initializer should fail.
    guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else
    os_log("Unable to decode the name for a player object.", log: OSLog.default, type: .debug)
    return nil


    let number = aDecoder.decodeObject(forKey: PropertyKey.number) as? String
    let localpresent = aDecoder.decodeBool(forKey: PropertyKey.present)

    // Must call designated initializer.
    self.init(name:name, number:number, present: localpresent)



    func encode(with aCoder: NSCoder)
    aCoder.encode(name, forKey: PropertyKey.name)
    aCoder.encode(number, forKey: PropertyKey.number)
    aCoder.encode(ispresent, forKey: PropertyKey.present)



    In Swift 4+ I'd prefer the native Codable protocol over constrained NSCoding.




    • NSCoding requires an class inherited from NSObject.


    • Codable can be used for any struct, class and enum which conforms to the protocol.





    share|improve this answer













    It's very easy to save a Bool if you are using the proper API.



    In terms of NSCoding a Bool is not an object, there is a decodeBool(forKey method.



    required convenience init?(coder aDecoder: NSCoder) 

    // The name is required. If we cannot decode a name string, the initializer should fail.
    guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else
    os_log("Unable to decode the name for a player object.", log: OSLog.default, type: .debug)
    return nil


    let number = aDecoder.decodeObject(forKey: PropertyKey.number) as? String
    let localpresent = aDecoder.decodeBool(forKey: PropertyKey.present)

    // Must call designated initializer.
    self.init(name:name, number:number, present: localpresent)



    func encode(with aCoder: NSCoder)
    aCoder.encode(name, forKey: PropertyKey.name)
    aCoder.encode(number, forKey: PropertyKey.number)
    aCoder.encode(ispresent, forKey: PropertyKey.present)



    In Swift 4+ I'd prefer the native Codable protocol over constrained NSCoding.




    • NSCoding requires an class inherited from NSObject.


    • Codable can be used for any struct, class and enum which conforms to the protocol.






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 15 '18 at 15:29









    vadianvadian

    153k17163189




    153k17163189












    • Thanks for all the quick answers. I'll convert to using Codable, which I think will also solve my other challenge around saving nested arrays. Thanks again everyone!

      – Sam Hawksworth
      Nov 15 '18 at 18:45

















    • Thanks for all the quick answers. I'll convert to using Codable, which I think will also solve my other challenge around saving nested arrays. Thanks again everyone!

      – Sam Hawksworth
      Nov 15 '18 at 18:45
















    Thanks for all the quick answers. I'll convert to using Codable, which I think will also solve my other challenge around saving nested arrays. Thanks again everyone!

    – Sam Hawksworth
    Nov 15 '18 at 18:45





    Thanks for all the quick answers. I'll convert to using Codable, which I think will also solve my other challenge around saving nested arrays. Thanks again everyone!

    – Sam Hawksworth
    Nov 15 '18 at 18:45













    0














    Use decodeBool(forKey key: String) instead of decodeObject(forKey: String)



    DecodeBool decodes and returns a boolean value that was previously encoded with encode(_:forKey:) and associated with the string key.



    aCoder.encode(true, forKey: PropertyKey.present)
    aCoder.decodeBool(forKey: PropertyKey.present)





    share|improve this answer



























      0














      Use decodeBool(forKey key: String) instead of decodeObject(forKey: String)



      DecodeBool decodes and returns a boolean value that was previously encoded with encode(_:forKey:) and associated with the string key.



      aCoder.encode(true, forKey: PropertyKey.present)
      aCoder.decodeBool(forKey: PropertyKey.present)





      share|improve this answer

























        0












        0








        0







        Use decodeBool(forKey key: String) instead of decodeObject(forKey: String)



        DecodeBool decodes and returns a boolean value that was previously encoded with encode(_:forKey:) and associated with the string key.



        aCoder.encode(true, forKey: PropertyKey.present)
        aCoder.decodeBool(forKey: PropertyKey.present)





        share|improve this answer













        Use decodeBool(forKey key: String) instead of decodeObject(forKey: String)



        DecodeBool decodes and returns a boolean value that was previously encoded with encode(_:forKey:) and associated with the string key.



        aCoder.encode(true, forKey: PropertyKey.present)
        aCoder.decodeBool(forKey: PropertyKey.present)






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 15 '18 at 15:30









        Raul MantillaRaul Mantilla

        1295




        1295



























            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%2f53322413%2fcant-save-bool-in-swift%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







            這個網誌中的熱門文章

            Barbados

            How to read a connectionString WITH PROVIDER in .NET Core?

            Node.js Script on GitHub Pages or Amazon S3