Created
August 25, 2011 16:41
-
-
Save seanlilmateus/1171111 to your computer and use it in GitHub Desktop.
how to use NSCoding with MacRuby
This file contains 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
#!/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