Can't retrieve data after storing to disk using NSKeyedArchiver - objective-c

I'm storing a custom object in a dictionary which i'm then saving to disk using NSKeyedArchiver. In the same method where I save the data, I do a quick test at the end to make sure I can load the data but everything comes out null. Why is this happening? I've been following the instructions in this tutorial: http://cocoadevcentral.com/articles/000084.php
/** Interface of viewcontroller**/
#import "User.h"
#interface BWViewController : UIViewController
{
IBOutlet UITextField *userNameField;
IBOutlet UITextField *passwordField;
IBOutlet UILabel * loginStatus;
}
#property (nonatomic, copy) NSString *holdPassword, *holdUserName;
-(IBAction)signUpButton;
-(IBAction)loginButton;
-(NSString*) pathForDataFile;
-(void) saveDataToDisk:(User*) someUser;
-(User *) loadDataFromDisk:(NSString*) theKey;
#end
/**Implementation file **/
#import "BWViewController.h"
#interface BWViewController ()
#end
#implementation BWViewController
#synthesize holdPassword,holdUserName;
-(IBAction)signUpButton
{
User * firstUser = [[User alloc] init];
firstUser.userName = userNameField.text;
firstUser.password = passwordField.text;
/**To save to file**/
[self saveDataToDisk:firstUser];
loginStatus.text = #"Thanks for signing up";
}
-(NSString*) pathForDataFile
{
NSFileManager * fileManager = [NSFileManager defaultManager];
NSString *folder =#"~/Library/Application Support/signUpApp/";
folder = [folder stringByExpandingTildeInPath];
if([fileManager fileExistsAtPath:folder] == NO)
{
[fileManager createFileAtPath:folder contents:nil attributes:nil];
}
NSString *fileName = #"signUpApp.demo";
return [folder stringByAppendingPathComponent:fileName];
}
-(void) saveDataToDisk:(User*) someUser
{
User * savingUser = someUser;
NSString * path = [self pathForDataFile];
NSMutableDictionary * rootObject = [NSMutableDictionary dictionary];
[rootObject setValue:savingUser forKey:userNameField.text];
[NSKeyedArchiver archiveRootObject:rootObject toFile:path];
NSLog(#"saving user to disk %#", savingUser.userName);
/**Testing the load process**/
User * testLoadUser;
NSMutableDictionary *unRootObject;
unRootObject = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
testLoadUser = [unRootObject valueForKey:userNameField.text];
NSLog(#"Testing the unarchive %# and %#", testLoadUser.userName, testLoadUser.password);
}
/**User implementation file**/
#import "User.h"
#implementation User
#synthesize userName, password;
- (void) encodeWithCoder: (NSCoder *)coder
{
[coder encodeObject: userName forKey:#"username"];
[coder encodeObject: password forKey:#"password"];
}
- (id) initWithCoder: (NSCoder *)coder
{
if (self = [super init])
{
self.userName = [coder decodeObjectForKey:#"username"];
self.password = [coder decodeObjectForKey:#"password"];
}
return self;
}
#end

This looks like iOS code, but you're using a Mac OS X convention for determining the folder for the path. In iOS, you should use the Documents folder.
For iOS, the path for the filename in the Documents folder should be:
- (NSString*) pathForDataFile
{
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *path = [documentsPath stringByAppendingString:#"signUpApp.demo"];
return path;
}
I'd also suggest checking the return code from archiveRootObject method, to confirm whether the archive succeeded or not. No point in going further if that failed.
Also, in your old pathForDataFile, you're calling createFileAtPath:contents:attributes:, but I suspect you intended createDirectoryAtURL:withIntermediateDirectories:attributes:error:. The former is for creating a file, and the latter is for creating a folder. And your code is trying to create a folder.

Quick things you can check..
1) IS file is Actually created on the location ?
2) Is there any data (random chars) in that file ?
3) Is your code contains <NSCopying> protocol in your user.h class?
4) Make sure you don't have - (id) initWithCoder: (NSCoder *)coder and - (void) encodeWithCoder: (NSCoder *)coder in your header file.

Related

Is there any way to emulate user's input in XCTest function?

I have method which expects user's input
#implementation TeamFormation
- (void)run {
NSFileHandle *kbd = [NSFileHandle fileHandleWithStandardInput];
NSData *inputData = [kbd availableData];
NSString *option = [[[NSString alloc] initWithData:inputData
encoding:NSUTF8StringEncoding] substringToIndex:1];
NSLog(#"%#",option);
}
#end
Then I would like to cover this method by a test case
#interface TeamFormationTests : XCTestCase
#end
#implementation TeamFormationTests
- (void)testTeamFormation {
TeamFormation *teamFormation = [TeamFormation new];
[teamFormation run];
// emulate user's input here
}
#end
So, how to emulate user's input in test case function?
You have many options how to achieve this. Two obvious below.
Change run to accept an argument
- (void)run to - (void)runWithFileHandle:(NSFileHandle *)handle
your app code can pass stdin filehandle
your test code can pass handle to a file with desired input
Mock it with protocol
Create DataProvider protocol:
#protocol DataProvider
#property(readonly, copy) NSData *availableData;
#end
Make NSFileHandle to conform to this protocol:
#interface NSFileHandle (AvailableDataProvider) <DataProvider>
#end
Store an object implementing this protocol on TeamFormation:
#interface TeamFormation : NSObject
#property (nonatomic, nonnull, strong) id<DataProvider> dataProvider;
- (NSString *)run;
#end
By default, use stdin file handle:
#implementation TeamFormation
- (instancetype)init {
if ((self = [super init]) == nil) {
return nil;
}
_dataProvider = [NSFileHandle fileHandleWithStandardInput];
return self;
}
- (NSString *)run {
NSData *inputData = [self.dataProvider availableData];
return [[[NSString alloc] initWithData:inputData encoding:NSUTF8StringEncoding] substringToIndex:1];
}
#end
Create TestDataProvider in your test:
#interface TestDataProvider: NSObject<DataProvider>
#property (nonatomic, strong, nonnull) NSData *dataToProvide;
#end
#implementation TestDataProvider
- (instancetype)init {
if ((self = [super init]) == nil) {
return nil;
}
_dataToProvide = [NSData new];
return self;
}
- (NSData *)availableData {
return _dataToProvide;
}
#end
And use it in TestFormationTests:
#implementation TeamFormationTests
- (void)testFormationRun {
TestDataProvider *dataProvider = [TestDataProvider new];
TeamFormation *formation = [TeamFormation new];
formation.dataProvider = dataProvider;
XCTAssertThrows([formation run]);
dataProvider.dataToProvide = [#"foo" dataUsingEncoding:NSUTF8StringEncoding];
XCTAssertEqualObjects([formation run], #"f");
dataProvider.dataToProvide = [#"bar" dataUsingEncoding:NSUTF8StringEncoding];
XCTAssertEqualObjects([formation run], #"b");
}
#end

Issue with writing XMLDocument

I have a non doc-based app with table view with two columns, whose Value bindings are bound to two properties of the arrangedObjects of an array controller. I have a NSMutableArray in my AppDelegate that hold the data, as well as the corresponding #property and #synthesize. I implement key-value-coding accessor methods and use those when inserting data to the array in order to generate KVO notifications. I fill up my array with some NSDictionary objects from xml file. I've got all that working (modify, remove and add items), but what I'd like to do is write it back to xml file.
xmlData writeToFile:fileName atomically:YES
is writing to disk, but don't reflect changes when editing table view. There must be some tiny little thing I am forgetting. What is it?
Any suggestions would be very nice!
The code:
// AppDelegate.h
#import <Cocoa/Cocoa.h>
#interface AppDelegate : NSObject <NSApplicationDelegate>{
NSXMLDocument *xmlDoc;
NSXMLElement *root;
NSMutableArray *children;
}
#property (assign) IBOutlet NSWindow *window;
#property (nonatomic, copy)NSArray *children;
- (void)setChildren:(NSArray *)newChildren;
- (NSUInteger)countOfChildren;
- (id)objectInChildrenAtIndex:(NSUInteger)index;
- (void)insertObject:(id)object inChildrenAtIndex:(NSUInteger)index;
- (void)removeObjectFromChildrenAtIndex:(NSUInteger)index;
- (IBAction)addObject:(id)sender;
- (IBAction)saveXMLToFile:(id)sender;
- (void) populateTable;
#end
// AppDelegate.m
#import "AppDelegate.h"
#implementation AppDelegate
-(void) addObjectToChildren:(id)object{
[self insertObject:object inChildrenAtIndex:[self countOfChildren]];
}
#synthesize children;
- (id)init{
self = [super init];
if (self) {
children = [[NSMutableArray alloc] init];
}
return self;
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{
[self populateTable];
}
#pragma mark - Indexed Accessors
- (void)setChildren:(NSArray *)newChildren{
if (children!=newChildren) {
children=[newChildren mutableCopy];
}
}
-(NSUInteger)countOfChildren{
return [self.children count];
}
-(id)objectInChildrenAtIndex:(NSUInteger)index{
return [self.children objectAtIndex:index];
}
- (void)insertObject:(id)object inChildrenAtIndex:(NSUInteger)index{
[children insertObject:object atIndex:index];
}
-(void)removeObjectFromChildrenAtIndex:(NSUInteger)index{
[children removeObjectAtIndex:index];
}
#pragma mark -
-(void)populateTable{
NSError *error=nil;
NSString *pathname = [#"~/myFile.xml" stringByExpandingTildeInPath];
NSURL *url = [NSURL fileURLWithPath:pathname];
xmlDoc = [[NSXMLDocument alloc] initWithContentsOfURL:url options:NSXMLDocumentTidyXML error:&error];
root = [xmlDoc rootElement];
NSArray *array=[root nodesForXPath:#"number" error:&error];
NSMutableArray *mArray=[[NSMutableArray alloc]init];
for (NSXMLElement *element in array) {
NSMutableDictionary *dict=[NSMutableDictionary dictionaryWithObjectsAndKeys:[element stringValue],#"id",#"number", #"name", nil];
[mArray addObject:dict];
}
[self setChildren:[NSArray arrayWithArray:mArray]];
}
#pragma mark - Actions
- (IBAction)addObject:(id)sender {
NSMutableDictionary *dict=[NSMutableDictionary dictionaryWithObjectsAndKeys:#"0",#"id",#"number", #"name", nil];
NSXMLElement *element=[[NSXMLElement alloc]initWithName:[dict objectForKey:#"name"] stringValue:[dict objectForKey:#"id"]];
[root insertChild:element atIndex:[self countOfChildren]];
[self addObjectToChildren:dict];
}
- (IBAction)saveXMLToFile:(id)sender {
NSString *fileName = [#"~/myFile.xml" stringByExpandingTildeInPath];
NSData *xmlData = [xmlDoc XMLDataWithOptions:NSXMLNodePrettyPrint];
if (![xmlData writeToFile:fileName atomically:YES]) {
NSBeep();
NSLog(#"Could not write document out...");
}
}
#end
The xml file:
<root>
<number>0</number>
<number>1</number>
<number>2</number>
<number>3</number>
<number>4</number>
<number>5</number>
</root>
When you change values in the tableview the underlying array is updated but not your XML document. You need to update your XML document or recreate it from the array to hold edited values.

CoreData, transient attribute and EXC_BAD_ACCESS.

I'm trying to build simple file browser and i'm stuck.
I defined classes, build window, add controllers, views.. Everything works but only ONE time.
Selecting again Folder in NSTableView or trying to get data from Folder.files causing silent EXC_BAD_ACCESS (code=13, address0x0) from main.
Info about files i keep outside of CoreData, in simple class, I don't want to save them:
#import <Foundation/Foundation.h>
#interface TPDrawersFileInfo : NSObject
#property (nonatomic, retain) NSString * filename;
#property (nonatomic, retain) NSString * extension;
#property (nonatomic, retain) NSDate * creation;
#property (nonatomic, retain) NSDate * modified;
#property (nonatomic, retain) NSNumber * isFile;
#property (nonatomic, retain) NSNumber * size;
#property (nonatomic, retain) NSNumber * label;
+(TPDrawersFileInfo *) initWithURL: (NSURL *) url;
#end
#implementation TPDrawersFileInfo
+(TPDrawersFileInfo *) initWithURL: (NSURL *) url {
TPDrawersFileInfo * new = [[TPDrawersFileInfo alloc] init];
if (new!=nil) {
NSFileManager * fileManager = [NSFileManager defaultManager];
NSError * error;
NSDictionary * infoDict = [fileManager attributesOfItemAtPath: [url path] error:&error];
id labelValue = nil;
[url getResourceValue:&labelValue forKey:NSURLLabelNumberKey error:&error];
new.label = labelValue;
new.size = [infoDict objectForKey: #"NSFileSize"];
new.modified = [infoDict objectForKey: #"NSFileModificationDate"];
new.creation = [infoDict objectForKey: #"NSFileCreationDate"];
new.isFile = [NSNumber numberWithBool:[[infoDict objectForKey:#"NSFileType"] isEqualToString:#"NSFileTypeRegular"]];
new.extension = [url pathExtension];
new.filename = [[url lastPathComponent] stringByDeletingPathExtension];
}
return new;
}
Next I have class Folder, which is NSManagesObject subclass
// Managed Object class to keep info about folder content
#interface Folder : NSManagedObject {
NSArray * _files;
}
#property (nonatomic, retain) NSArray * files; // Array with TPDrawersFileInfo objects
#property (nonatomic, retain) NSString * url; // url of folder
-(void) reload; //if url changed, load file info again.
#end
#implementation Folder
#synthesize files = _files;
#dynamic url;
-(void)awakeFromInsert {
[self addObserver:self forKeyPath:#"url" options:NSKeyValueObservingOptionNew context:#"url"];
}
-(void)awakeFromFetch {
[self addObserver:self forKeyPath:#"url" options:NSKeyValueObservingOptionNew context:#"url"];
}
-(void)prepareForDeletion {
[self removeObserver:self forKeyPath:#"url"];
}
-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (context == #"url") {
[self reload];
}
}
-(void) reload {
NSMutableArray * result = [NSMutableArray array];
NSError * error = nil;
NSFileManager * fileManager = [NSFileManager defaultManager];
NSString * percented = [self.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSArray * listDir = [fileManager contentsOfDirectoryAtURL: [NSURL URLWithString: percented]
includingPropertiesForKeys: [NSArray arrayWithObject: NSURLCreationDateKey ]
options:NSDirectoryEnumerationSkipsHiddenFiles
error:&error];
if (error!=nil) {NSLog(#"Error <%#> reading <%#> content", error, self.url);}
for (id fileURL in listDir) {
TPDrawersFileInfo * fi = [TPDrawersFileInfo initWithURL:fileURL];
[result addObject: fi];
}
_files = [NSArray arrayWithArray:result];
}
#end
In app delegate i defined
#interface TPAppDelegate : NSObject <NSApplicationDelegate> {
IBOutlet NSArrayController * foldersController;
Folder * currentFolder;
}
- (IBAction)chooseDirectory:(id)sender; // choose folder
and
- (Folder * ) getFolderObjectForPath: path {
//gives Folder object if already exist or nil if not
.....
}
- (IBAction)chooseDirectory:(id)sender {
//Opens panel, asking for url
NSOpenPanel * panel = [NSOpenPanel openPanel];
[panel setCanChooseDirectories:YES];
[panel setCanChooseFiles:NO];
[panel setMessage:#"Choose folder to show:"];
NSURL * currentDirectory;
if ([panel runModal] == NSOKButton)
{
currentDirectory = [[panel URLs] objectAtIndex:0];
}
Folder * folderObject = [self getFolderObjectForPath:[currentDirectory path]];
if (folderObject) {
//if exist:
currentFolder = folderObject;
} else {
// create new one
Folder * newFolder = [NSEntityDescription
insertNewObjectForEntityForName:#"Folder"
inManagedObjectContext:self.managedObjectContext];
[newFolder setValue:[currentDirectory path] forKey:#"url"];
[foldersController addObject:newFolder];
currentFolder = newFolder;
}
[foldersController setSelectedObjects:[NSArray arrayWithObject:currentFolder]];
}
Please help ;)
Ha!
_files = [NSArray arrayWithArray:result];
Should be:
_files = [[NSArray arrayWithArray:result] retain];

iOS persistent storage strategy

I'm developing an app which will save data to the local file system. The data that will be saved will be mostly NSString and NSDate. The data will not be saved that often, perhaps new data will be entered 10 times at a typical usage. The data should also of course be retrievable (CRUD)
How should I save this data? First of all is it necessary to model these objects? If not should I use property lists? Or SQLLite3?
Else should I archive the class models? Use SQLLite3?
EDIT: I accidentally left out some vital information about the app. Actually my app will be having 2 data models which have an aggregated relationship. So my first data model (lets call it DataA) which will have a NSString and NSDate will also have a reference to the second data model (lets call it DataB) which itself will consist of a NSString and a NSArray. So it gets a little more complicated now. If an object from DataB gets deleted it should of course cease to exist in DataA (but the rest of DataA should be left untouched)
This kind of data seems to be very simple to store and retrieve and does not have any other dependencies such as a horridly complex object graph.
You should store this data in a flat file or in NSUserDefaults.
I'll give you an example of both, using object archiving with the use of the NSCoding protocol:
#interface ApplicationData <NSCopying, NSCoding> {}
#property (nonatomic, strong) NSDate *someDate;
#property (nonatomic, strong) NSDate *someOtherDate;
#property (nonatomic, copy) NSString *someString;
#property (nonatomic, copy) NSString *someOtherString;
#end
#implementation ApplicationData
#synthesize someDate = _someDate, someOtherDate = _someOtherDate, someString = _someString, someOtherString = _someOtherString;
- (NSArray *)keys {
static dispatch_once_t once;
static NSArray *keys = nil;
dispatch_once(&once, ^{
keys = [NSArray arrayWithObjects:#"someString", #"someOtherString", #"someDate", #"someOtherDate", nil];
});
return keys;
}
- (id) copyWithZone:(NSZone *) zone {
ApplicationData *data = [[[self class] allocWithZone:zone] init];
if(data) {
data.someString = _someString;
data.someOtherString = _someOtherString;
data.someDate = _someDate;
data.someOtherDate = _someOtherDate;
//...
}
return data;
}
- (void) encodeWithCoder:(NSCoder *) coder {
[super encodeWithCoder:coder];
NSDictionary *pairs = [self dictionaryWithValuesForKeys:[self keys]];
for(NSString *key in keys) {
[coder encodeObject:[pairs objectForKey:key] forKey:key];
}
}
- (id) initWithCoder:(NSCoder *) decoder {
self = [super initWithCoder:decoder];
if(self) {
for(NSString *key in [self keys]) {
[self setValue:[decoder decodeObjectForKey:key] forKey:key];
}
}
return self;
}
#end
Then, say in your application delegate, you can do this:
#interface AppDelegate (Persistence)
#property (nonatomic, strong) ApplicationData *data;
- (void)saveApplicationDataToFlatFile;
- (void)loadApplicationDataFromFlatFile;
- (void)saveApplicationDataToUserDefaults;
- (void)loadApplicationDataFromUserDefaults;
#end
#implementation AppDelegate (Persistence)
#synthesize data;
- (NSString *)_dataFilePath {
static NSString *path = nil;
static dispatch_once_t once;
dispatch_once(&once, ^{
path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) stringByAppendingPathComponent:#"xAppData.dat"];
});
return path;
}
- (void)loadApplicationDataFromUserDefaults {
NSData *archivedData = [[NSUserDefaults standardUserDefaults] objectForKey:#"appData"];
self.data = [NSKeyedUnarchiver unarchiveObjectWithData:archivedData];
}
- (void)saveApplicationDataToUserDefaults {
NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject:self.data];
[[NSUserDefaults standardUserDefaults] setObject:archivedData forKey:#"appData"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)loadApplicationDataFromFlatFile {
NSData *archivedData = [NSData dataWithContentsOfFile:[self _dataFilePath]];
self.data = [NSKeyedUnarchiver unarchiveObjectWithData:archivedData];
}
- (void)saveApplicationDataToFlatFile {
NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject:self.data];
[archivedData writeToFile:[self _dataFilePath] atomically:YES];
}
#end
Disclaimer: I have not tested this code.
NSUserDefault is good choice if you have only a limited set of data.
But if you consider filtering and fetching, then you should have a look to Core Data to store objects.
Even if the object graph is minimal you will gain cached object management and free undo/redo management.
I would suggest that you go with NSUserDefaults. It's surely the best approach to store information pertaining to your app and any app related data. Check the documentation !!

Issue with save file to Documents NSMutableArray with NSObjects

I'm a newbie iOS developer.
I wrote a small application that save an NSMutableArray array with my objects that derived from NSObject.
Application do the save but the file isn't created in document directory and application can't read.
this issue is both on the simulator and my iPhone 3gs 4.2.1
My NSMutableArray definition inside the appDelegate class:
#property (nonatomic,retain, readwrite) NSMutableArray *places;
My NSObject class:
#import <Foundation/Foundation.h>
#interface Place : NSObject {
NSString *name;
NSString *location;
}
-(id) init:(NSString *)name: (NSString *)location;
#property (retain,nonatomic,readwrite) NSString *name;
#property (retain,nonatomic,readwrite) NSString *location;
#end
My StorageService library class:
#import "StorageService.h"
#implementation StorageService
-(id) init {
self = [super init];
if (self != nil) {
}
return self;
}
-(void) saveArrayToFile:(NSString*) filename : (NSMutableArray *)arrayToSave{
// get full path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fullPath = [paths objectAtIndex:0];
fullPath = [fullPath stringByAppendingPathComponent:filename];
NSLog(#"Save in %#",fullPath);
[arrayToSave writeToFile:fullPath atomically:YES];
}
-(NSMutableArray*) readArrayFromFile:(NSString *)filename {
// get full path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fullPath = [paths objectAtIndex:0];
fullPath = [fullPath stringByAppendingPathComponent:filename];
if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath]) {
NSMutableArray *data = [[NSMutableArray alloc] initWithContentsOfFile:fullPath];
if (data == nil) {
data = [[NSMutableArray alloc] init];
}
NSLog(#"Read from %#",fullPath);
return data;
} else {
NSMutableArray *data = [[NSMutableArray alloc] initWithContentsOfFile:fullPath];
return data;
}
}
-(void) dealloc {
[super dealloc];
}
#end
and My functions in the appDelegate:
-(void) saveApplicationData {
[self.storageService saveArrayToFile : PLACES_FILE : self.places];
}
-(void) loadApplicationData {
self.places = [self.storageService readArrayFromFile:PLACES_FILE];
}
Here is my class that holds constant to filename:
#import <Foundation/Foundation.h>
extern NSString * const PLACES_FILE = #"Places.dat";
#interface ApplicationConstants : NSObject {
}
#end
So what is wrong?
Thank you guys.
What you want is to let Place conform to the NSCoding protocol, to allow for serialization to and from files (and in memory data if wanted)
Extend Place as (I have also changed the name of the init method as your name was against every naming practice iOS has):
#interface Place : NSObject <NSCoding> {
NSString *name;
NSString *location;
}
-(id)initWithName:(NSString *)name location:(NSString *)location;
#property (retain,nonatomic,readwrite) NSString *name;
#property (retain,nonatomic,readwrite) NSString *location;
#end
Your implementation is quite simple but you also need to implement two methods defined by the NSCoding protocol:
#implementation Place
#synthesize name, location;
-(id)initWithName:(NSString *)aName location:(NSString *)aLocation {
self = [super init];
if (self) {
self.name = aName;
self.location = aLocation;
}
return self;
}
-(id)initWithWithCoder:(NSCoder)decoder {
self = [super initWithCoder:decoder];
if (self) {
self.name = [decoder decodeObjectForKey:#"name"];
self.location = [decoder decodeObjectForKey:#"location";
}
return self;
}
-(void)encodeWithCoder:(NSCoder*)encoder {
[encoder encodeObject:self.name forKey:#"name"];
[encoder encodeObject:self.location forKey:#"location"];
[super encodeWithCoder:encoder];
}
#end
With this in place, saving the places array to disk is as easy as:
[NSKeyedArchiver archiveRootObject:places toFile:path];
And decoding just as easy:
places = [[KSKeyUnarchiver unarchiveObjectWithFile:path] retain];
To use writeToFile objects in array need to be plist capable type (NSDate, NSDate, NSString, NSArray, NSDictionary)
Implement NSCoding on the objects in array and use NSKeyedArchiver to serialize/deserialize.
write:
[NSKeyedArchiver archiveRootObject:myArray toFile:self.places];
read:
[NSKeyedUnarchiver unarchiveObjectWithFile:path];
More info can be found here:
Persisting Custom Objects