SlideShare a Scribd company logo
1 of 15
Download to read offline
Boutique product development company
It is amazing what you can accomplish when you have a client-centric team to deliver outstanding products.
Archiving
Sajid Hussain | Software Evangelist
Archiving
Topics covered in the presentation




     •   Archiving With XML Property Lists
     •   Archiving With NS Keyed Archiver
     •   Writing Encoding and Decoding
         Methods
     •   Encoding and Decoding Basic Data
         Types in Keyed Archives
     •   Using NS Data to Create Custom
         Archives
     •   Using Archiver to Copy Objects
     •   Final Wrods
                                             Sajid Hussain | Software Evangelist
Archiving


Archiving




       Objective-C terms, archiving is the process of saving one or
       more objects in a format so that they can later be restored.
       Often this involves writing the object(s) to a file so it can
       subsequently be read back in.




                                                  Sajid Hussain | Software Evangelist
Archiving

Archiving with XML Property Lists
If your objects are of type NSString, NSDictionary, NSArray, NSDate, NSData, or NSNumber, you can use
the writeToFile:atomically: method implemented in these classes to write your data to a file.

                                                 Program # 1
                                       intmain (intargc, char *argv[]) {
                        NSAutoreleasePool* pool = [[NSAutoreleasePoolalloc] init];
 NSDictionary*glossary = [NSDictionarydictionaryWithObjectsAndKeys:@”A class defined so other
           classes can inherit from it.”, @”abstract class”, @”To implement all the methods defined in a
                     protocol”, @”adopt”, @”Storing an object for later use. “, @”archiving”, nil];
                      if ([glossary writeToFile: @”glossary”atomically: YES] == NO)
                                       NSLog(@”Save to file failed!”);
                                                 [pool drain];
                                                   return 0;
                                                       }

The writeToFile:atomically: message is sent to your dictionary object glossary, causing the dictionary to be
written to the file glossary in the form of a property list. The atomically parameter is set to YES, meaning
that you want the write operation to be done to a temporary backup file first; once successful, the final data
is to be moved to the specified file named glossary.




                                                                         Sajid Hussain | Software Evangelist
Archiving


Archiving with XML Property Lists Cont..
  If you examine the contents of the glossary file created by Program # 1, it looks
  like this:

  <?xml version=”1.0” encoding=”UTF-8”?>
  <!DOCTYPE plist PUBLIC “-//Apple Computer//DTD PLIST 1.0//EN”“http://
            www.apple.com/DTDs/PropertyList-1.0.dtd”>
  <plist version=”1.0”>
  <dict>
  <key>abstract class</key>
  <string>A class defined so other classes can inherit from it.</string>
  <key>adopt</key>
  <string>To implement all the methods defined in a
  protocol</string><key>archiving</key>
  <string>Storing an object for later use. </string>
  </dict>
  </plist>


                                                        Sajid Hussain | Software Evangelist
Archiving


Archiving with XML Property Lists Cont..

  Program # 2
  intmain (intargc, char *argv[]) {
  NSAutoreleasePool* pool = [[NSAutoreleasePoolalloc] init];
  NSDictionary*glossary;glossary = [NSDictionarydictionaryWithContentsOfFile:
  @”glossary”];
  for ( NSString *key in glossary )
  NSLog(@”%@: %@”, key, [glossary objectForKey: key]);
  [pool drain];
  return 0;
  }

  Program # 2 Output
  archiving: Storing an object for later use.
  abstract class: A class defined so other classes can inherit from it.
  adopt: To implement all the methods defined in a protocol



                                                          Sajid Hussain | Software Evangelist
Archiving

Archiving with NS Keyed Archiver

 Program # 3
 intmain (intargc, char *argv[]) {
 NSAutoreleasePool* pool = [[NSAutoreleasePoolalloc] init];
 NSDictionary*glossary = [NSDictionarydictionaryWithObjectsAndKeys: @”A class defined so other
               classes can inherit from it”, @”abstract class”, @”To implement all the methods defined in a
               protocol”, @”adopt”, @”Storing an object for later use”, @”archiving”, nil];
 [NSKeyedArchiverarchiveRootObject: glossary toFile: @”glossary.archive”];                       [pool release];
 return 0;
 }

 Program # 4
 intmain (intargc, char *argv[]) {
 NSAutoreleasePool* pool = [[NSAutoreleasePoolalloc] init];
 NSDictionary*glossary;
 glossary = [NSKeyedUnarchiverunarchiveObjectWithFile: @”glossary.archive”];
 for ( NSString *key in glossary )
 NSLog(@”%@: %@”, key, [glossary objectForKey: key]);
 [pool drain];
 return 0;
 }

 Program # 4 Output
 abstract class: A class defined so other classes can inherit from it.
 adopt: To implement all the methods defined in a protocol
 archiving: Storing an object for later use.


                                                                                   Sajid Hussain | Software Evangelist
Archiving


Writing Encoding and Decoding Method
  Basic Objective-C class objects such as NSString, NSArray, NSDictionary, NSSet, NSDate,NSNumber, and NSData
  can be archived and restored in the manner just described. That includes nested objects as well, such as an array
  containing a string or even other array objects. To archive objects other than those listed, you must tell the system how
  to archive, or encode, your objects, and also how to unarchive, or decode, them. This is done by adding
  encodeWithCoder: and initWithCoder: methods to your class definitions, according to the <NSCoding> protocol.

  @interface Foo: NSObject<NSCoding>{
  NSString*strVal; intintVal; float floatVal;
  }
  @property (copy, nonatomic) NSString *strVal;
  @property intintVal;
  @property float floatVal;
  @end

  // Definition for our Fooclass
  @implementation Foo
  @synthesize strVal, intVal, floatVal;
  -(void) encodeWithCoder: (NSCoder *) encoder {
  [encoder encodeObject: strValforKey: @”FoostrVal”];
  [encoder encodeInt: intValforKey: @”FoointVal”];
  [encoder encodeFloat: floatValforKey: @”FoofloatVal”];
  }
  -(id) initWithCoder: (NSCoder *) decoder {
  strVal= [[decoder decodeObjectForKey: @”FoostrVal”] retain];
  intVal= [decoder decodeIntForKey: @”FoointVal”];
  floatVal= [decoder decodeFloatForKey: @”FoofloatVal”];
  return self;
                                                                                    Sajid Hussain | Software Evangelist
Archiving

Writing Encoding and Decoding Method Cont..
  Program # 5Test Program
  intmain (intargc, char *argv[]) {
  NSAutoreleasePool* pool = [[NSAutoreleasePoolalloc] init];
  Foo*myFoo1 = [[Fooalloc] init];
  Foo*myFoo2;[myFoo1 setStrVal: @”This is the string”];
  [myFoo1 setIntVal: 12345];
  [myFoo1 setFloatVal: 98.6];
  [NSKeyedArchiver archiveRootObject: myFoo1 toFile: @”foo.arch”];
  myFoo2 = [NSKeyedUnarchiverunarchiveObjectWithFile: @”foo.arch”];
  NSLog(@”%@n%in%g”, [myFoo2 strVal], [myFoo2 intVal], [myFoo2 floatVal]);
  [myFoo1 release];
  [pool drain];
  return 0;
  }

  Program # 5 Output
  This is the string
  12345
  98.6

  The encodeWithCoder: method is invoked each time the archiver wants to encode an object from the specified class,
  and the method tells it how to do so. In a similar manner, the initWithCoder: method is invoked each time an object from
  the specified class is to be decoded. if you knew the super- class of your class conformed to the NSCoding protocol,
  you should start your encoding method with a statement like the following to make sure your inherited instance
  variables are encoded: [super encodeWithCoder: encoder]; The only time a conflict might arise is if the same key is
  used for a subclass of an object being encoded. To prevent this from happening, you can insert the class name in front
  of the instance variable name when composing the key for the archive.
                                                                                  Sajid Hussain | Software Evangelist
Archiving

Encoding and Decoding Basic Data Types in Keyed Archives

  For basic underlying C data types (such as integers and floats), you use one of the methods listed in the following
  Table. The decoder method, initWithCoder: works in reverse: You use decodeObject:forKey: to decode basic Objective-
  C classes and the appropriate decoder method shown in following Table for the basic data types.


                  Encoder                                        Decoder
                  encodeBool:forKey:                             decodeBool:forKey:
                  encodeInt:forKey:                              decodeInt:forKey:
                  encodeInt32:forKey:                            decodeInt32:forKey:
                  encodeInt64: forKey:                           decodeInt64:forKey:
                  encodeFloat:forKey:                            decodeFloat:forKey:
                  encodeDouble:forKey:                           decodeDouble:forKey:
  Some of the basic data types, such as char, short, long, and long long, are not listed in the Table; you must determine
  the size of your data object and use the appropriate routine. For example, a short int is normally 16 bits, an int and long
  can be 32 or 64 bits, and a long long is 64 bits. (You can use the sizeof operator to determine the size of any data type.)
  So to archive a short int, store it in an int first and then archive it with encodeInt:forKey:. Reverse the process to get it
  back: Use decodeInt:forKey: and then assign it to your short int variable.



                                                                                     Sajid Hussain | Software Evangelist
Archiving

Using NSData to Create Custom Archives
  Perhaps you want to collect some or all of your objects and store them in a single archive file.

  Program # 6
  intmain (intargc, char *argv[]) {
  NSAutoreleasePool* pool = [[NSAutoreleasePoolalloc] init];
  Foo*myFoo1 = [[Fooalloc] init];
  NSMutableData*dataArea;NSKeyedArchiver *archiver;
  [myFoo1 setStrVal: @”This is the string”];
  [myFoo1 setIntVal: 12345];
  [myFoo1 setFloatVal: 98.6];
               // Set up a data area and connect it to an NSKeyedArchiver object
  dataArea= [NSMutableData data];
  archiver= [[NSKeyedArchiveralloc] initForWritingWithMutableData: dataArea];
  // Now we can begin to archive objects
  [archiverencodeObject: myFoo1 forKey: @”myfoo1”];
  [archiverfinishEncoding];
               // Write the archived data are to a file
  if ( [dataAreawriteToFile: @”myArchive” atomically: YES] == NO)
  NSLog(@”Archiving failed!”);
  [archiver release];
  [myFoo1 release];
  [pool drain];
  return 0;
                                                                        Sajid Hussain | Software Evangelist
Archiving

Using NSData to Create Custom Archives Cont..

  Program # 7
  intmain (intargc, char *argv[]) {
  NSAutoreleasePool* pool = [[NSAutoreleasePoolalloc] init];
  NSData*dataArea;
  NSKeyedUnarchiver*unarchiver;
  Foo*myFoo1;
  // Read in the archive and connect an NSKeyedUnarchiver object to it
  dataArea= [NSDatadataWithContentsOfFile: @”myArchive”];
  if (! dataArea) {
  NSLog(@“Can’t read back archive file!”);
                            Return (1);
  }
  unarchiver= [[NSKeyedUnarchiveralloc] initForReadingWithData: dataArea];
  // Decode the objects we previously stored in the archive
  myFoo1 = [unarchiverdecodeObjectForKey: @”myfoo1”];
  [unarchiver finishDecoding];
  [unarchiver release];
  // Verify that the restore was successful
  } NSLog(“%@n%in%g”, [myFoo1 strVal], [myFoo1 intVal], [myFoo1 floatVal]);
  [pool release];
  return 0;


                                                                   Sajid Hussain | Software Evangelist
Archiving

Using Archiver to Copy Objects
  Program # 8
  intmain (intargc, char *argv[]) {
  NSAutoreleasePool*pool = [[NSAutoreleasePoolalloc] init];
  NSData*data;
  NSMutableArray*dataArray = [NSMutableArrayarrayWithObjects:[NSMutableStringstringWithString: @”one”],
                                                    [NSMutableStringstringWithString: @”two”], [NSMutableStringstringWithString: @”three”], nil];
  NSMutableArray*dataArray2;
  NSMutableString*mStr;
                   // Make a deep copy using the archiver
                   data = [NSKeyedArchiverarchivedDataWithRootObject: dataArray];
                   dataArray2 = [NSKeyedUnarchiverunarchiveObjectWithData: data];
  mStr= [dataArray2 objectAtIndex: 0];
                   [mStrappendString: @”ONE”];
  NSLog(@”dataArray: “);
                   for ( NSString *elem in dataArray)
  NSLog(“%@”, elem);
  NSLog(@”ndataArray2: “);
  for ( NSString *elem in dataArray2 )
  NSLog(“%@”, elem);
                   [pool drsin];
                   return 0;
  }

  Program # 8 Output
  dataArray:
  one
  two
  Three
  dataArray2:
  oneONE
  two
  three

                                                                                                  Sajid Hussain | Software Evangelist
Archiving

Final Words

     •      If you want to store simple values, serialization (using an
            NSDictionary, for example) is a fine way to go. If you want to store
            an object graph of arbitrary types, with uniqueness and mutability
            preserved, using archives (with NSCoder, for example) is your best
            bet.


     • NSCodingis a powerful way to serialize objects so that you can
       pass them between processes or save it to a file. Implement the
       NSCoding protocol on your custom objects that you want to
       serialize, then use NSKeyedArchiver to serialize them and
       NSKeyedUnarchiver to deserialize them.




                                                       Sajid Hussain | Software Evangelist

More Related Content

What's hot

CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26Bilal Ahmed
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know Norberto Leite
 
Configuring Mahout Clustering Jobs - Frank Scholten
Configuring Mahout Clustering Jobs - Frank ScholtenConfiguring Mahout Clustering Jobs - Frank Scholten
Configuring Mahout Clustering Jobs - Frank Scholtenlucenerevolution
 
Java Development with MongoDB
Java Development with MongoDBJava Development with MongoDB
Java Development with MongoDBScott Hernandez
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBMongoDB
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Hermann Hueck
 
descriptive programming
descriptive programmingdescriptive programming
descriptive programmingAnand Dhana
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++nsm.nikhil
 
Gpu programming with java
Gpu programming with javaGpu programming with java
Gpu programming with javaGary Sieling
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaMongoDB
 
Java development with MongoDB
Java development with MongoDBJava development with MongoDB
Java development with MongoDBJames Williams
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 featuresindia_mani
 
Puppet overview
Puppet overviewPuppet overview
Puppet overviewMike_Foto
 
Going beyond Django ORM limitations with Postgres
Going beyond Django ORM limitations with PostgresGoing beyond Django ORM limitations with Postgres
Going beyond Django ORM limitations with PostgresCraig Kerstiens
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCDrsebbe
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...Claudio Capobianco
 

What's hot (20)

CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Python Objects
Python ObjectsPython Objects
Python Objects
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
Configuring Mahout Clustering Jobs - Frank Scholten
Configuring Mahout Clustering Jobs - Frank ScholtenConfiguring Mahout Clustering Jobs - Frank Scholten
Configuring Mahout Clustering Jobs - Frank Scholten
 
Java Development with MongoDB
Java Development with MongoDBJava Development with MongoDB
Java Development with MongoDB
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8
 
descriptive programming
descriptive programmingdescriptive programming
descriptive programming
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++
 
Gpu programming with java
Gpu programming with javaGpu programming with java
Gpu programming with java
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and Morphia
 
Java development with MongoDB
Java development with MongoDBJava development with MongoDB
Java development with MongoDB
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 
Puppet overview
Puppet overviewPuppet overview
Puppet overview
 
11 bytecode
11 bytecode11 bytecode
11 bytecode
 
Going beyond Django ORM limitations with Postgres
Going beyond Django ORM limitations with PostgresGoing beyond Django ORM limitations with Postgres
Going beyond Django ORM limitations with Postgres
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
 
Java 7 & 8 New Features
Java 7 & 8 New FeaturesJava 7 & 8 New Features
Java 7 & 8 New Features
 

Viewers also liked

Learning as a creative professional
Learning as a creative professionalLearning as a creative professional
Learning as a creative professionalConfiz
 
Ts threading
Ts   threadingTs   threading
Ts threadingConfiz
 
Ts drupal6 module development v0.2
Ts   drupal6 module development v0.2Ts   drupal6 module development v0.2
Ts drupal6 module development v0.2Confiz
 
Learning as a creative professional
Learning as a creative professionalLearning as a creative professional
Learning as a creative professionalConfiz
 
Agile training workshop
Agile training workshopAgile training workshop
Agile training workshopConfiz
 
Kanban Task Manager Single for Outlook
Kanban Task Manager Single for OutlookKanban Task Manager Single for Outlook
Kanban Task Manager Single for OutlookPeter Kalmstrom
 
Ts seo t ech session
Ts   seo t ech sessionTs   seo t ech session
Ts seo t ech sessionConfiz
 
Ts android supporting multiple screen
Ts   android supporting multiple screenTs   android supporting multiple screen
Ts android supporting multiple screenConfiz
 
TkXel Portfolio
TkXel Portfolio TkXel Portfolio
TkXel Portfolio TkXel
 
Design Multiple Screen android
Design Multiple Screen androidDesign Multiple Screen android
Design Multiple Screen androidChaiwoot Phrombutr
 
Software testing methods, levels and types
Software testing methods, levels and typesSoftware testing methods, levels and types
Software testing methods, levels and typesConfiz
 
Web services with laravel
Web services with laravelWeb services with laravel
Web services with laravelConfiz
 

Viewers also liked (12)

Learning as a creative professional
Learning as a creative professionalLearning as a creative professional
Learning as a creative professional
 
Ts threading
Ts   threadingTs   threading
Ts threading
 
Ts drupal6 module development v0.2
Ts   drupal6 module development v0.2Ts   drupal6 module development v0.2
Ts drupal6 module development v0.2
 
Learning as a creative professional
Learning as a creative professionalLearning as a creative professional
Learning as a creative professional
 
Agile training workshop
Agile training workshopAgile training workshop
Agile training workshop
 
Kanban Task Manager Single for Outlook
Kanban Task Manager Single for OutlookKanban Task Manager Single for Outlook
Kanban Task Manager Single for Outlook
 
Ts seo t ech session
Ts   seo t ech sessionTs   seo t ech session
Ts seo t ech session
 
Ts android supporting multiple screen
Ts   android supporting multiple screenTs   android supporting multiple screen
Ts android supporting multiple screen
 
TkXel Portfolio
TkXel Portfolio TkXel Portfolio
TkXel Portfolio
 
Design Multiple Screen android
Design Multiple Screen androidDesign Multiple Screen android
Design Multiple Screen android
 
Software testing methods, levels and types
Software testing methods, levels and typesSoftware testing methods, levels and types
Software testing methods, levels and types
 
Web services with laravel
Web services with laravelWeb services with laravel
Web services with laravel
 

Similar to Ts archiving

iOS: Using persistant storage
iOS: Using persistant storageiOS: Using persistant storage
iOS: Using persistant storageJussi Pohjolainen
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdfSudhanshiBakre1
 
Null Bachaav - May 07 Attack Monitoring workshop.
Null Bachaav - May 07 Attack Monitoring workshop.Null Bachaav - May 07 Attack Monitoring workshop.
Null Bachaav - May 07 Attack Monitoring workshop.Prajal Kulkarni
 
Apache Spark Tutorial
Apache Spark TutorialApache Spark Tutorial
Apache Spark TutorialAhmet Bulut
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2NAILBITER
 
Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)
Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)
Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)Takayuki Shimizukawa
 
Sphinx autodoc - automated api documentation - PyCon.MY 2015
Sphinx autodoc - automated api documentation - PyCon.MY 2015Sphinx autodoc - automated api documentation - PyCon.MY 2015
Sphinx autodoc - automated api documentation - PyCon.MY 2015Takayuki Shimizukawa
 
Spark schema for free with David Szakallas
Spark schema for free with David SzakallasSpark schema for free with David Szakallas
Spark schema for free with David SzakallasDatabricks
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applicationsjeromevdl
 
2017-06-22 Documentation as code
2017-06-22 Documentation as code2017-06-22 Documentation as code
2017-06-22 Documentation as codeJérémie Bresson
 
Future-proof Development for Classic SharePoint
Future-proof Development for Classic SharePointFuture-proof Development for Classic SharePoint
Future-proof Development for Classic SharePointBob German
 
Don't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesDon't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesJamund Ferguson
 
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018Codemotion
 
Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)
Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)
Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)Takayuki Shimizukawa
 
Javascript internals
Javascript internalsJavascript internals
Javascript internalsNir Noy
 
Spark Summit EU talk by Ross Lawley
Spark Summit EU talk by Ross LawleySpark Summit EU talk by Ross Lawley
Spark Summit EU talk by Ross LawleySpark Summit
 
How To Connect Spark To Your Own Datasource
How To Connect Spark To Your Own DatasourceHow To Connect Spark To Your Own Datasource
How To Connect Spark To Your Own DatasourceMongoDB
 

Similar to Ts archiving (20)

iOS: Using persistant storage
iOS: Using persistant storageiOS: Using persistant storage
iOS: Using persistant storage
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdf
 
Null Bachaav - May 07 Attack Monitoring workshop.
Null Bachaav - May 07 Attack Monitoring workshop.Null Bachaav - May 07 Attack Monitoring workshop.
Null Bachaav - May 07 Attack Monitoring workshop.
 
Objective c
Objective cObjective c
Objective c
 
Apache Spark Tutorial
Apache Spark TutorialApache Spark Tutorial
Apache Spark Tutorial
 
iPhone Seminar Part 2
iPhone Seminar Part 2iPhone Seminar Part 2
iPhone Seminar Part 2
 
Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)
Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)
Sphinx autodoc - automated API documentation (EuroPython 2015 in Bilbao)
 
Sphinx autodoc - automated api documentation - PyCon.MY 2015
Sphinx autodoc - automated api documentation - PyCon.MY 2015Sphinx autodoc - automated api documentation - PyCon.MY 2015
Sphinx autodoc - automated api documentation - PyCon.MY 2015
 
Spark schema for free with David Szakallas
Spark schema for free with David SzakallasSpark schema for free with David Szakallas
Spark schema for free with David Szakallas
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applications
 
2017-06-22 Documentation as code
2017-06-22 Documentation as code2017-06-22 Documentation as code
2017-06-22 Documentation as code
 
Future-proof Development for Classic SharePoint
Future-proof Development for Classic SharePointFuture-proof Development for Classic SharePoint
Future-proof Development for Classic SharePoint
 
Don't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesDon't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax Trees
 
iOS Application Development
iOS Application DevelopmentiOS Application Development
iOS Application Development
 
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
Jan Stępień - GraalVM: Fast, Polyglot, Native - Codemotion Berlin 2018
 
iOS Session-2
iOS Session-2iOS Session-2
iOS Session-2
 
Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)
Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)
Sphinx autodoc - automated API documentation (PyCon APAC 2015 in Taiwan)
 
Javascript internals
Javascript internalsJavascript internals
Javascript internals
 
Spark Summit EU talk by Ross Lawley
Spark Summit EU talk by Ross LawleySpark Summit EU talk by Ross Lawley
Spark Summit EU talk by Ross Lawley
 
How To Connect Spark To Your Own Datasource
How To Connect Spark To Your Own DatasourceHow To Connect Spark To Your Own Datasource
How To Connect Spark To Your Own Datasource
 

More from Confiz

DMAIC-Six sigma process Improvement Approach
DMAIC-Six sigma process Improvement ApproachDMAIC-Six sigma process Improvement Approach
DMAIC-Six sigma process Improvement ApproachConfiz
 
What is UFT? HP's unified functional testing.
What is UFT? HP's unified functional testing.What is UFT? HP's unified functional testing.
What is UFT? HP's unified functional testing.Confiz
 
Sqa, test scenarios and test cases
Sqa, test scenarios and test casesSqa, test scenarios and test cases
Sqa, test scenarios and test casesConfiz
 
Solid principles of oo design
Solid principles of oo designSolid principles of oo design
Solid principles of oo designConfiz
 
Entity framework code first
Entity framework code firstEntity framework code first
Entity framework code firstConfiz
 
Security testing presentation
Security testing presentationSecurity testing presentation
Security testing presentationConfiz
 
Advance text rendering in i os
Advance text rendering in i osAdvance text rendering in i os
Advance text rendering in i osConfiz
 
Photoshop manners
Photoshop mannersPhotoshop manners
Photoshop mannersConfiz
 
Monkey talk
Monkey talkMonkey talk
Monkey talkConfiz
 
An insight to microsoft platform
An insight to microsoft platformAn insight to microsoft platform
An insight to microsoft platformConfiz
 
Ts branching over the top
Ts   branching over the topTs   branching over the top
Ts branching over the topConfiz
 

More from Confiz (11)

DMAIC-Six sigma process Improvement Approach
DMAIC-Six sigma process Improvement ApproachDMAIC-Six sigma process Improvement Approach
DMAIC-Six sigma process Improvement Approach
 
What is UFT? HP's unified functional testing.
What is UFT? HP's unified functional testing.What is UFT? HP's unified functional testing.
What is UFT? HP's unified functional testing.
 
Sqa, test scenarios and test cases
Sqa, test scenarios and test casesSqa, test scenarios and test cases
Sqa, test scenarios and test cases
 
Solid principles of oo design
Solid principles of oo designSolid principles of oo design
Solid principles of oo design
 
Entity framework code first
Entity framework code firstEntity framework code first
Entity framework code first
 
Security testing presentation
Security testing presentationSecurity testing presentation
Security testing presentation
 
Advance text rendering in i os
Advance text rendering in i osAdvance text rendering in i os
Advance text rendering in i os
 
Photoshop manners
Photoshop mannersPhotoshop manners
Photoshop manners
 
Monkey talk
Monkey talkMonkey talk
Monkey talk
 
An insight to microsoft platform
An insight to microsoft platformAn insight to microsoft platform
An insight to microsoft platform
 
Ts branching over the top
Ts   branching over the topTs   branching over the top
Ts branching over the top
 

Ts archiving

  • 1. Boutique product development company It is amazing what you can accomplish when you have a client-centric team to deliver outstanding products.
  • 2. Archiving Sajid Hussain | Software Evangelist
  • 3. Archiving Topics covered in the presentation • Archiving With XML Property Lists • Archiving With NS Keyed Archiver • Writing Encoding and Decoding Methods • Encoding and Decoding Basic Data Types in Keyed Archives • Using NS Data to Create Custom Archives • Using Archiver to Copy Objects • Final Wrods Sajid Hussain | Software Evangelist
  • 4. Archiving Archiving Objective-C terms, archiving is the process of saving one or more objects in a format so that they can later be restored. Often this involves writing the object(s) to a file so it can subsequently be read back in. Sajid Hussain | Software Evangelist
  • 5. Archiving Archiving with XML Property Lists If your objects are of type NSString, NSDictionary, NSArray, NSDate, NSData, or NSNumber, you can use the writeToFile:atomically: method implemented in these classes to write your data to a file. Program # 1 intmain (intargc, char *argv[]) { NSAutoreleasePool* pool = [[NSAutoreleasePoolalloc] init]; NSDictionary*glossary = [NSDictionarydictionaryWithObjectsAndKeys:@”A class defined so other classes can inherit from it.”, @”abstract class”, @”To implement all the methods defined in a protocol”, @”adopt”, @”Storing an object for later use. “, @”archiving”, nil]; if ([glossary writeToFile: @”glossary”atomically: YES] == NO) NSLog(@”Save to file failed!”); [pool drain]; return 0; } The writeToFile:atomically: message is sent to your dictionary object glossary, causing the dictionary to be written to the file glossary in the form of a property list. The atomically parameter is set to YES, meaning that you want the write operation to be done to a temporary backup file first; once successful, the final data is to be moved to the specified file named glossary. Sajid Hussain | Software Evangelist
  • 6. Archiving Archiving with XML Property Lists Cont.. If you examine the contents of the glossary file created by Program # 1, it looks like this: <?xml version=”1.0” encoding=”UTF-8”?> <!DOCTYPE plist PUBLIC “-//Apple Computer//DTD PLIST 1.0//EN”“http:// www.apple.com/DTDs/PropertyList-1.0.dtd”> <plist version=”1.0”> <dict> <key>abstract class</key> <string>A class defined so other classes can inherit from it.</string> <key>adopt</key> <string>To implement all the methods defined in a protocol</string><key>archiving</key> <string>Storing an object for later use. </string> </dict> </plist> Sajid Hussain | Software Evangelist
  • 7. Archiving Archiving with XML Property Lists Cont.. Program # 2 intmain (intargc, char *argv[]) { NSAutoreleasePool* pool = [[NSAutoreleasePoolalloc] init]; NSDictionary*glossary;glossary = [NSDictionarydictionaryWithContentsOfFile: @”glossary”]; for ( NSString *key in glossary ) NSLog(@”%@: %@”, key, [glossary objectForKey: key]); [pool drain]; return 0; } Program # 2 Output archiving: Storing an object for later use. abstract class: A class defined so other classes can inherit from it. adopt: To implement all the methods defined in a protocol Sajid Hussain | Software Evangelist
  • 8. Archiving Archiving with NS Keyed Archiver Program # 3 intmain (intargc, char *argv[]) { NSAutoreleasePool* pool = [[NSAutoreleasePoolalloc] init]; NSDictionary*glossary = [NSDictionarydictionaryWithObjectsAndKeys: @”A class defined so other classes can inherit from it”, @”abstract class”, @”To implement all the methods defined in a protocol”, @”adopt”, @”Storing an object for later use”, @”archiving”, nil]; [NSKeyedArchiverarchiveRootObject: glossary toFile: @”glossary.archive”]; [pool release]; return 0; } Program # 4 intmain (intargc, char *argv[]) { NSAutoreleasePool* pool = [[NSAutoreleasePoolalloc] init]; NSDictionary*glossary; glossary = [NSKeyedUnarchiverunarchiveObjectWithFile: @”glossary.archive”]; for ( NSString *key in glossary ) NSLog(@”%@: %@”, key, [glossary objectForKey: key]); [pool drain]; return 0; } Program # 4 Output abstract class: A class defined so other classes can inherit from it. adopt: To implement all the methods defined in a protocol archiving: Storing an object for later use. Sajid Hussain | Software Evangelist
  • 9. Archiving Writing Encoding and Decoding Method Basic Objective-C class objects such as NSString, NSArray, NSDictionary, NSSet, NSDate,NSNumber, and NSData can be archived and restored in the manner just described. That includes nested objects as well, such as an array containing a string or even other array objects. To archive objects other than those listed, you must tell the system how to archive, or encode, your objects, and also how to unarchive, or decode, them. This is done by adding encodeWithCoder: and initWithCoder: methods to your class definitions, according to the <NSCoding> protocol. @interface Foo: NSObject<NSCoding>{ NSString*strVal; intintVal; float floatVal; } @property (copy, nonatomic) NSString *strVal; @property intintVal; @property float floatVal; @end // Definition for our Fooclass @implementation Foo @synthesize strVal, intVal, floatVal; -(void) encodeWithCoder: (NSCoder *) encoder { [encoder encodeObject: strValforKey: @”FoostrVal”]; [encoder encodeInt: intValforKey: @”FoointVal”]; [encoder encodeFloat: floatValforKey: @”FoofloatVal”]; } -(id) initWithCoder: (NSCoder *) decoder { strVal= [[decoder decodeObjectForKey: @”FoostrVal”] retain]; intVal= [decoder decodeIntForKey: @”FoointVal”]; floatVal= [decoder decodeFloatForKey: @”FoofloatVal”]; return self; Sajid Hussain | Software Evangelist
  • 10. Archiving Writing Encoding and Decoding Method Cont.. Program # 5Test Program intmain (intargc, char *argv[]) { NSAutoreleasePool* pool = [[NSAutoreleasePoolalloc] init]; Foo*myFoo1 = [[Fooalloc] init]; Foo*myFoo2;[myFoo1 setStrVal: @”This is the string”]; [myFoo1 setIntVal: 12345]; [myFoo1 setFloatVal: 98.6]; [NSKeyedArchiver archiveRootObject: myFoo1 toFile: @”foo.arch”]; myFoo2 = [NSKeyedUnarchiverunarchiveObjectWithFile: @”foo.arch”]; NSLog(@”%@n%in%g”, [myFoo2 strVal], [myFoo2 intVal], [myFoo2 floatVal]); [myFoo1 release]; [pool drain]; return 0; } Program # 5 Output This is the string 12345 98.6 The encodeWithCoder: method is invoked each time the archiver wants to encode an object from the specified class, and the method tells it how to do so. In a similar manner, the initWithCoder: method is invoked each time an object from the specified class is to be decoded. if you knew the super- class of your class conformed to the NSCoding protocol, you should start your encoding method with a statement like the following to make sure your inherited instance variables are encoded: [super encodeWithCoder: encoder]; The only time a conflict might arise is if the same key is used for a subclass of an object being encoded. To prevent this from happening, you can insert the class name in front of the instance variable name when composing the key for the archive. Sajid Hussain | Software Evangelist
  • 11. Archiving Encoding and Decoding Basic Data Types in Keyed Archives For basic underlying C data types (such as integers and floats), you use one of the methods listed in the following Table. The decoder method, initWithCoder: works in reverse: You use decodeObject:forKey: to decode basic Objective- C classes and the appropriate decoder method shown in following Table for the basic data types. Encoder Decoder encodeBool:forKey: decodeBool:forKey: encodeInt:forKey: decodeInt:forKey: encodeInt32:forKey: decodeInt32:forKey: encodeInt64: forKey: decodeInt64:forKey: encodeFloat:forKey: decodeFloat:forKey: encodeDouble:forKey: decodeDouble:forKey: Some of the basic data types, such as char, short, long, and long long, are not listed in the Table; you must determine the size of your data object and use the appropriate routine. For example, a short int is normally 16 bits, an int and long can be 32 or 64 bits, and a long long is 64 bits. (You can use the sizeof operator to determine the size of any data type.) So to archive a short int, store it in an int first and then archive it with encodeInt:forKey:. Reverse the process to get it back: Use decodeInt:forKey: and then assign it to your short int variable. Sajid Hussain | Software Evangelist
  • 12. Archiving Using NSData to Create Custom Archives Perhaps you want to collect some or all of your objects and store them in a single archive file. Program # 6 intmain (intargc, char *argv[]) { NSAutoreleasePool* pool = [[NSAutoreleasePoolalloc] init]; Foo*myFoo1 = [[Fooalloc] init]; NSMutableData*dataArea;NSKeyedArchiver *archiver; [myFoo1 setStrVal: @”This is the string”]; [myFoo1 setIntVal: 12345]; [myFoo1 setFloatVal: 98.6]; // Set up a data area and connect it to an NSKeyedArchiver object dataArea= [NSMutableData data]; archiver= [[NSKeyedArchiveralloc] initForWritingWithMutableData: dataArea]; // Now we can begin to archive objects [archiverencodeObject: myFoo1 forKey: @”myfoo1”]; [archiverfinishEncoding]; // Write the archived data are to a file if ( [dataAreawriteToFile: @”myArchive” atomically: YES] == NO) NSLog(@”Archiving failed!”); [archiver release]; [myFoo1 release]; [pool drain]; return 0; Sajid Hussain | Software Evangelist
  • 13. Archiving Using NSData to Create Custom Archives Cont.. Program # 7 intmain (intargc, char *argv[]) { NSAutoreleasePool* pool = [[NSAutoreleasePoolalloc] init]; NSData*dataArea; NSKeyedUnarchiver*unarchiver; Foo*myFoo1; // Read in the archive and connect an NSKeyedUnarchiver object to it dataArea= [NSDatadataWithContentsOfFile: @”myArchive”]; if (! dataArea) { NSLog(@“Can’t read back archive file!”); Return (1); } unarchiver= [[NSKeyedUnarchiveralloc] initForReadingWithData: dataArea]; // Decode the objects we previously stored in the archive myFoo1 = [unarchiverdecodeObjectForKey: @”myfoo1”]; [unarchiver finishDecoding]; [unarchiver release]; // Verify that the restore was successful } NSLog(“%@n%in%g”, [myFoo1 strVal], [myFoo1 intVal], [myFoo1 floatVal]); [pool release]; return 0; Sajid Hussain | Software Evangelist
  • 14. Archiving Using Archiver to Copy Objects Program # 8 intmain (intargc, char *argv[]) { NSAutoreleasePool*pool = [[NSAutoreleasePoolalloc] init]; NSData*data; NSMutableArray*dataArray = [NSMutableArrayarrayWithObjects:[NSMutableStringstringWithString: @”one”], [NSMutableStringstringWithString: @”two”], [NSMutableStringstringWithString: @”three”], nil]; NSMutableArray*dataArray2; NSMutableString*mStr; // Make a deep copy using the archiver data = [NSKeyedArchiverarchivedDataWithRootObject: dataArray]; dataArray2 = [NSKeyedUnarchiverunarchiveObjectWithData: data]; mStr= [dataArray2 objectAtIndex: 0]; [mStrappendString: @”ONE”]; NSLog(@”dataArray: “); for ( NSString *elem in dataArray) NSLog(“%@”, elem); NSLog(@”ndataArray2: “); for ( NSString *elem in dataArray2 ) NSLog(“%@”, elem); [pool drsin]; return 0; } Program # 8 Output dataArray: one two Three dataArray2: oneONE two three Sajid Hussain | Software Evangelist
  • 15. Archiving Final Words • If you want to store simple values, serialization (using an NSDictionary, for example) is a fine way to go. If you want to store an object graph of arbitrary types, with uniqueness and mutability preserved, using archives (with NSCoder, for example) is your best bet. • NSCodingis a powerful way to serialize objects so that you can pass them between processes or save it to a file. Implement the NSCoding protocol on your custom objects that you want to serialize, then use NSKeyedArchiver to serialize them and NSKeyedUnarchiver to deserialize them. Sajid Hussain | Software Evangelist