//
//  persist.m
//  persist
//
#import <Foundation/Foundation.h>
#import <Foundation/NSCoder.h>

#define		valueKey	@"valueKey"

/*	Data class to hold the mutated data	*/
@interface DataClass : NSObject<NSCoding>
{
@private
	NSString* value;
}
@property (readonly,nonatomic,retain) NSString* value;

-(id)init;
+(id)DataClassFromValue:(NSString*)value;

-(id)initWithCoder:(NSCoder*)decoder;
-(void)encodeWithCoder:(NSCoder*)encoder;
@end


@implementation DataClass

@synthesize value;
+(id)DataClassFromValue:(NSString*)value
{
	DataClass* dc = [[DataClass alloc]init];
	[dc setValue:value];
	return [dc autorelease];
}
-(id)init
{
	if( ! (self=[super init]) )
		return self;
	
	return self;
}
-(id)initWithCoder:(NSCoder*)decoder
{
	self = [[DataClass alloc] init];
	
	value = [[decoder decodeObjectForKey:valueKey ] retain];
	NSLog( @"Loaded string value: %@", value );
	
	return self;
}

-(void)encodeWithCoder:(NSCoder*)encoder
{
	[encoder encodeObject:value forKey:valueKey ];
	NSLog( @"encodeWithCoder, saved string : %@",value );
}

-(void)setValue:(NSString*)newValue
{
	NSLog( @">>DataClass setValue '%@' now renamed to '%@'", value,newValue );
	if(value)
		[value release];
	
	value = [newValue retain];
}
@end


int main(int argc, const char * argv[])
{
	NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
	
	const char* someUTfEight = "english -> γερμανικών δυνάμεων στον <-some Greek";
	
	NSString* mixedString = [NSString stringWithUTF8String:someUTfEight ];
	NSLog( @"Set String value: %@", mixedString );
	
	DataClass* dc = [DataClass DataClassFromValue: mixedString];
	NSLog( @"Data class value: %@", dc.value );
	
	/*	Persist the data class		*/
	NSString* filename = @"./persists.model";
	BOOL created = [NSKeyedArchiver archiveRootObject: dc 
										       toFile: filename ];
	if( NO==created )
		NSLog( @" !!! Faield to create NSKeyedArchiver of alertsModel !!!" );
	else
		NSLog( @"-- Saved DataClass to disk." );
	
	// Loading project
	DataClass* dcLoaded = [NSKeyedUnarchiver unarchiveObjectWithFile:filename ];
	NSLog( @"Loaded Data class value: %@", dcLoaded.value );
	
	[pool release];
    return 0;
}
