Created
August 11, 2012 17:42
-
-
Save rapind/3325934 to your computer and use it in GitHub Desktop.
NSCodable Module for RubyMotion serializable / NSCode -able classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # This is an example of using the NSCodable module. | |
| class Post | |
| include NSCodable | |
| attr_accessor :id, :message | |
| end | |
| # Create a new post. | |
| post = Post.new(:id => 4, :message => 'Some random message') | |
| # Serialize the post using NS Archiver. | |
| post_as_data = NSKeyedArchiver.archivedDataWithRootObject(post) | |
| # Deserialize the post using NS Unarchiver. | |
| post2 = NSKeyedUnarchiver.unarchiveObjectWithData(post_as_data) | |
| # Save the post to the user's cache. | |
| defaults = NSUserDefaults.standardUserDefaults | |
| defaults["saved_post"] = post_as_data |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Simply include this module into your classes that you want to be encoded with NSCode (serialized for temporary cache). | |
| module NSCodable | |
| # Accepts any public property assignment via hash initialization. | |
| def initialize(attributes = {}) | |
| attributes.each do |key, val| | |
| self.public_send("#{key}=", val) | |
| end | |
| end | |
| # Initilizes an object using the NSDecoder. | |
| def initWithCoder(decoder) | |
| self.init | |
| # Loop through the attribute writers. | |
| methods.grep(/\w=:$/).each do |method| | |
| # Extract the key (attribute name). | |
| key = method.to_s.sub('=:', '') | |
| # Decode the attribute. | |
| self.send(method, decoder.decodeObjectForKey(key)) | |
| end | |
| self | |
| end | |
| # Encodes an object using the NSCode encoder. | |
| def encodeWithCoder(encoder) | |
| # Loop through the attribute writers. | |
| methods.grep(/\w=:$/).each do |method| | |
| # Extract the key (attribute name). | |
| key = method.to_s.sub('=:', '') | |
| # Encode the attribute. | |
| encoder.encodeObject(self.send(key), forKey: key) | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment