Skip to content

Instantly share code, notes, and snippets.

@seanlilmateus
Created August 25, 2011 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanlilmateus/1171111 to your computer and use it in GitHub Desktop.
Save seanlilmateus/1171111 to your computer and use it in GitHub Desktop.
how to use NSCoding with MacRuby
#!/usr/local/bin/macruby
framework 'Foundation'
class Note < NSObject
attr_accessor :title, :author, :published
def initialize(title, author, published)
self.conformsToProtocol(Protocol.protocolWithName('NSCoding'))
@title, @author, @published = title, author, published
# protocol NSCoding
end
def initWithCoder aDecoder
@title = aDecoder.decodeObjectForKey "title"
@author = aDecoder.decodeObjectForKey "author"
@published = aDecoder.decodeBoolForKey "published"
self
end
def encodeWithCoder anEncoder
anEncoder.encodeObject @title, forKey:"title"
anEncoder.encodeObject @author, forKey:"author"
anEncoder.encodeBool @published, forKey:"published"
self
end
end
# create notes array
notes = []
articles = [{title:"Agora", author:“author1", published: true},
{title:"thema", author:"author2", published: false},
{title:"Topic", author:"Caren", published: true}]
articles.each do |note|
notes << Note.new(note[:title],note[:author],note[:published])
end
# Given `notes` contains an array of Note objects
data = NSKeyedArchiver.archivedDataWithRootObject notes
NSUserDefaults.standardUserDefaults.setObject data, forKey:"notes"
p data
# Unarchiving is just as easy
notesData = NSUserDefaults.standardUserDefaults.objectForKey "notes"
notes = NSKeyedUnarchiver.unarchiveObjectWithData notesData
p notes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment