Skip to content

Instantly share code, notes, and snippets.

@rapind
Created August 11, 2012 17:42
Show Gist options
  • Select an option

  • Save rapind/3325934 to your computer and use it in GitHub Desktop.

Select an option

Save rapind/3325934 to your computer and use it in GitHub Desktop.
NSCodable Module for RubyMotion serializable / NSCode -able classes
# 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
# 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