SlideShare a Scribd company logo
iOS:	
  Persistant	
  Storage	
  

       Jussi	
  Pohjolainen	
  
Overview	
  
•  iOS	
  provides	
  many	
  ways	
  of	
  saving	
  and	
  loading	
  data	
  	
  
•  NSUserDefaults	
  
    –  Simple	
  mechanism	
  for	
  preferences	
  
•  Archiving	
  
    –  Save	
  and	
  load	
  data	
  model	
  object	
  a<ributes	
  from	
  file	
  
       system	
  
•  Wri;ng	
  to	
  File	
  System	
  
    –  Easy	
  mechanism	
  for	
  reading	
  and	
  wri@ng	
  bytes	
  
•  SQLite	
  
    –  Rela@onal	
  database	
  
NSUserDefaults	
  
•  Default	
  database	
  is	
  created	
  automa@cally	
  for	
  
   each	
  user	
  
•  Saves	
  and	
  loads	
  data	
  to	
  database	
  
•  At	
  run@me	
  caches	
  informa@on	
  to	
  avoid	
  having	
  to	
  
   open	
  connec@on	
  to	
  the	
  database	
  
    –  synchronize	
  method	
  will	
  save	
  cache	
  to	
  database	
  
    –  synchronize	
  method	
  is	
  invoked	
  at	
  periodic	
  intervals	
  
•  Methods	
  for	
  saving	
  and	
  loading	
  NSData,	
  
   NSString,	
  NSNumber,	
  NSDate,	
  NSArray	
  and	
  
   NSDic@onary	
  
    –  Any	
  other	
  object;	
  archive	
  it	
  to	
  NSData	
  
Example	
  NSUserDefaults:	
  Saving	
  
NSUserDefaults *defaults = [NSUserDefaults
standardUserDefaults];
[defaults setObject:firstName forKey:@"firstName"];
[defaults setObject:lastName forKey:@"lastname"];
[defaults synchronize];
Example	
  NSUserDefaults:	
  Loading	
  
NSUserDefaults *defaults =
      [NSUserDefaults standardUserDefaults];
NSString *firstName =
      [defaults objectForKey:@"firstName"];
NSString *lastName =
      [defaults objectForKey:@"lastname"];
Archiving	
  
•  NSUserDefaults	
  is	
  good	
  for	
  storing	
  simple	
  data	
  
•  If	
  the	
  applica@on	
  model	
  is	
  complex,	
  archiving	
  
   is	
  a	
  good	
  solu@on	
  
•  Archiving?	
  
    –  Saving	
  objects	
  (=instance	
  variables)	
  to	
  file	
  system	
  
•  Classes	
  that	
  are	
  archived	
  must	
  
    –  Conform	
  NSCoding	
  protocol	
  
    –  Implement	
  two	
  methods:	
  encodeWithCoder	
  and	
  
       initWithCoder	
  
Example	
  
@interface Person : NSObject <NSCoding>
{
    NSString* name;
    int id;
}

- (void) encodeWithCoder:(NSCoder* ) aCoder;
- (void) initWithCoder:(NSCoder* ) aDeCoder;

* * *

- (void) encodeWithCoder:(NSCoder* ) aCoder
{
    [aCoder encodeObject: name forKey:@"personName"];
    [aCoder encodeInt: id forKey:@"personId"];
}

- (void) initWithCoder:(NSCoder* ) aDeCoder
{
    self = [super init];
    if(self) {
        name = [aDecoder decodeObjectForKey:@"personName"];
        id   = [aDecoder decodeIntForKey:@"personId"];
    }
    return self;
}
About	
  Applica@on	
  Sandbox	
  
•  Every	
  iOS	
  app	
  has	
  its	
  own	
  applica@on	
  sandbox	
  
•  Sandbox	
  is	
  a	
  directory	
  on	
  the	
  filesystem	
  that	
  is	
  barricaded	
  
   from	
  the	
  rest	
  of	
  the	
  file	
  system	
  
•  Sandbox	
  directory	
  structure	
  
     –  Library/Preferences	
  
          •  Preferences	
  files.	
  Backed	
  up.	
  
     –  Tmp/	
  
          •  Temp	
  data	
  storage	
  on	
  run@me.	
  NSTemporaryDirectory	
  will	
  give	
  you	
  a	
  
             path	
  to	
  this	
  dir	
  
     –  Documents/	
  
          •  Write	
  data	
  for	
  permanent	
  storage.	
  Backed	
  up.	
  
     –  Library/Caches	
  
          •  Same	
  than	
  Documents	
  except	
  it’s	
  not	
  backed	
  up.	
  Example:	
  fetch	
  large	
  
             data	
  from	
  web	
  server	
  and	
  store	
  it	
  here.	
  
Archiving	
  to	
  Documents/	
  dir	
  
// Searches file system for a path that meets the criteria given by the
// arguments. On iOS the last two arguments are always the same! (Mac OS X has several
// more options)
//
// Returns array of strings, in iOS only one string in the array.
NSArray *documentDirectories =
     NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserFomainMask, YES);

// Fetch the only document directory found in the array
NSString *documentDirectory =
     [documentDirectories objectAtIndex:0];

// Add file name to the end of the array
NSString *path = [documentDirectory stringByAppendingPathComponent:@"file.archive"];
NSKeyedArchiver	
  and	
  
               NSKeyedUnarchiver	
  
•  NSKeyedArchiver	
  provides	
  a	
  way	
  to	
  encode	
  
   objects	
  into	
  a	
  file.	
  
       [NSKeyedArchiver archiveRootObject: someObject
                                   toFile: path];
•  NSKeyedUnarchiver	
  decodes	
  the	
  objects	
  from	
  
   file	
  
       someObject = [NSKeyedUnArchiver
                      unarchiveObjectWithFile: path];
Reading	
  and	
  Wri@ng	
  Files	
  
•  NSData	
  and	
  NSString	
  provides	
  easy	
  access	
  for	
  
   reading	
  and	
  wri@ng	
  bytes.	
  	
  
•  NSDic@onary	
  has	
  also	
  methods	
  for	
  saving	
  and	
  
   storing	
  the	
  dic@onary	
  to	
  property	
  list	
  (xml	
  file)	
  
•  Also	
  standard	
  file	
  I/O	
  func@ons	
  from	
  C	
  library	
  
   available	
  
    –  fopen,	
  fread,	
  fwrite	
  	
  
Wri@ng	
  to	
  File	
  System	
  using	
  NSData	
  
•  NSData	
  provides	
  convinient	
  methods	
  for	
  
   reading	
  and	
  wri@ng	
  to	
  file	
  system	
  
   –  - writeToFile:atomically
   –  + dataWithContentsOfFile
•  Example	
  
   –  [someData writeToFile:path atomically:YES]
   –  NSData* data = [NSData dataWithContestOfFile:
      path];

More Related Content

PPT
More than UI
PDF
Kudu and Rust
PPTX
Get docs from sp doc library
PPTX
ElasticSearch Basics
PDF
Redis the better NoSQL
PPTX
MongoDB
PPTX
MongoDb and NoSQL
DOCX
Format xls sheets Demo Mode
More than UI
Kudu and Rust
Get docs from sp doc library
ElasticSearch Basics
Redis the better NoSQL
MongoDB
MongoDb and NoSQL
Format xls sheets Demo Mode

What's hot (20)

PPT
Persistences
PDF
Building a userspace filesystem in node.js
PDF
(No)SQL Timing Attacks for Data Retrieval
PDF
A New MongoDB Sharding Architecture for Higher Availability and Better Resour...
PDF
Saving Data
PPTX
PDF
Шардинг в MongoDB, Henrik Ingo (MongoDB)
PPTX
04 data accesstechnologies
PDF
Android Data Persistence
PDF
Softshake - Offline applications
PDF
Terraform, Ansible or pure CloudFormation
PDF
BITS: Introduction to relational databases and MySQL - Schema design
PDF
Terraform, Ansible, or pure CloudFormation?
PPTX
PDF
Lucene InputFormat (lightning talk) - TriHUG December 10, 2013
PDF
Brief introduction of Slick
ODP
Web scraping with nutch solr part 2
PPTX
Puppet overview
PDF
Introduce leo-redundant-manager
PDF
Memory management
Persistences
Building a userspace filesystem in node.js
(No)SQL Timing Attacks for Data Retrieval
A New MongoDB Sharding Architecture for Higher Availability and Better Resour...
Saving Data
Шардинг в MongoDB, Henrik Ingo (MongoDB)
04 data accesstechnologies
Android Data Persistence
Softshake - Offline applications
Terraform, Ansible or pure CloudFormation
BITS: Introduction to relational databases and MySQL - Schema design
Terraform, Ansible, or pure CloudFormation?
Lucene InputFormat (lightning talk) - TriHUG December 10, 2013
Brief introduction of Slick
Web scraping with nutch solr part 2
Puppet overview
Introduce leo-redundant-manager
Memory management
Ad

Viewers also liked (7)

PDF
Intro to Asha UI
PDF
Expanding Programming Skills (C++): Intro to Course
PDF
iOS Selectors Blocks and Delegation
PDF
Compiling Qt Apps
PPT
Intro to Java Technology
PDF
Android Sensors
PDF
libGDX: Simple Frame Animation
Intro to Asha UI
Expanding Programming Skills (C++): Intro to Course
iOS Selectors Blocks and Delegation
Compiling Qt Apps
Intro to Java Technology
Android Sensors
libGDX: Simple Frame Animation
Ad

Similar to iOS: Using persistant storage (20)

PDF
Ts archiving
PPT
Connecting to a REST API in iOS
PDF
The Role of Atom/AtomPub in Digital Archive Services at The University of Tex...
PDF
09.Local Database Files and Storage on WP
PDF
Oracle forensics 101
PPTX
Hibernate in XPages
KEY
занятие8
PDF
Information Retrieval - Data Science Bootcamp
PDF
React Native Course - Data Storage . pdf
PDF
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
PDF
Using Document Databases with TYPO3 Flow
PPTX
INT 222.pptx
PPT
14 file handling
 
KEY
iOSDevCamp 2011 Core Data
PPTX
Elastic Search
PDF
Development of the irods rados plugin @ iRODS User group meeting 2014
PDF
From SQL to MongoDB
PDF
BlueStore: a new, faster storage backend for Ceph
PDF
Ceph Tech Talk: Bluestore
PPTX
Skillwise - Enhancing dotnet app
Ts archiving
Connecting to a REST API in iOS
The Role of Atom/AtomPub in Digital Archive Services at The University of Tex...
09.Local Database Files and Storage on WP
Oracle forensics 101
Hibernate in XPages
занятие8
Information Retrieval - Data Science Bootcamp
React Native Course - Data Storage . pdf
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
Using Document Databases with TYPO3 Flow
INT 222.pptx
14 file handling
 
iOSDevCamp 2011 Core Data
Elastic Search
Development of the irods rados plugin @ iRODS User group meeting 2014
From SQL to MongoDB
BlueStore: a new, faster storage backend for Ceph
Ceph Tech Talk: Bluestore
Skillwise - Enhancing dotnet app

More from Jussi Pohjolainen (20)

PDF
Moved to Speakerdeck
PDF
Java Web Services
PDF
Box2D and libGDX
PDF
libGDX: Screens, Fonts and Preferences
PDF
libGDX: Tiled Maps
PDF
libGDX: User Input and Frame by Frame Animation
PDF
Intro to Building Android Games using libGDX
PDF
Advanced JavaScript Development
PDF
Introduction to JavaScript
PDF
Introduction to AngularJS
PDF
libGDX: Scene2D
PDF
libGDX: Simple Frame Animation
PDF
libGDX: User Input
PDF
Implementing a Simple Game using libGDX
PDF
Building Android games using LibGDX
PDF
Android Threading
PDF
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
PDF
Creating Games for Asha - platform
PDF
Intro to Java ME and Asha Platform
PDF
Intro to PhoneGap
Moved to Speakerdeck
Java Web Services
Box2D and libGDX
libGDX: Screens, Fonts and Preferences
libGDX: Tiled Maps
libGDX: User Input and Frame by Frame Animation
Intro to Building Android Games using libGDX
Advanced JavaScript Development
Introduction to JavaScript
Introduction to AngularJS
libGDX: Scene2D
libGDX: Simple Frame Animation
libGDX: User Input
Implementing a Simple Game using libGDX
Building Android games using LibGDX
Android Threading
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Games for Asha - platform
Intro to Java ME and Asha Platform
Intro to PhoneGap

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Encapsulation theory and applications.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
cuic standard and advanced reporting.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Approach and Philosophy of On baking technology
DOCX
The AUB Centre for AI in Media Proposal.docx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
KodekX | Application Modernization Development
PPT
Teaching material agriculture food technology
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Cloud computing and distributed systems.
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Modernizing your data center with Dell and AMD
MYSQL Presentation for SQL database connectivity
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Encapsulation theory and applications.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Electronic commerce courselecture one. Pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
cuic standard and advanced reporting.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Spectral efficient network and resource selection model in 5G networks
Approach and Philosophy of On baking technology
The AUB Centre for AI in Media Proposal.docx
“AI and Expert System Decision Support & Business Intelligence Systems”
KodekX | Application Modernization Development
Teaching material agriculture food technology
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Cloud computing and distributed systems.
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
20250228 LYD VKU AI Blended-Learning.pptx
NewMind AI Monthly Chronicles - July 2025
Modernizing your data center with Dell and AMD

iOS: Using persistant storage

  • 1. iOS:  Persistant  Storage   Jussi  Pohjolainen  
  • 2. Overview   •  iOS  provides  many  ways  of  saving  and  loading  data     •  NSUserDefaults   –  Simple  mechanism  for  preferences   •  Archiving   –  Save  and  load  data  model  object  a<ributes  from  file   system   •  Wri;ng  to  File  System   –  Easy  mechanism  for  reading  and  wri@ng  bytes   •  SQLite   –  Rela@onal  database  
  • 3. NSUserDefaults   •  Default  database  is  created  automa@cally  for   each  user   •  Saves  and  loads  data  to  database   •  At  run@me  caches  informa@on  to  avoid  having  to   open  connec@on  to  the  database   –  synchronize  method  will  save  cache  to  database   –  synchronize  method  is  invoked  at  periodic  intervals   •  Methods  for  saving  and  loading  NSData,   NSString,  NSNumber,  NSDate,  NSArray  and   NSDic@onary   –  Any  other  object;  archive  it  to  NSData  
  • 4. Example  NSUserDefaults:  Saving   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:firstName forKey:@"firstName"]; [defaults setObject:lastName forKey:@"lastname"]; [defaults synchronize];
  • 5. Example  NSUserDefaults:  Loading   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSString *firstName = [defaults objectForKey:@"firstName"]; NSString *lastName = [defaults objectForKey:@"lastname"];
  • 6. Archiving   •  NSUserDefaults  is  good  for  storing  simple  data   •  If  the  applica@on  model  is  complex,  archiving   is  a  good  solu@on   •  Archiving?   –  Saving  objects  (=instance  variables)  to  file  system   •  Classes  that  are  archived  must   –  Conform  NSCoding  protocol   –  Implement  two  methods:  encodeWithCoder  and   initWithCoder  
  • 7. Example   @interface Person : NSObject <NSCoding> { NSString* name; int id; } - (void) encodeWithCoder:(NSCoder* ) aCoder; - (void) initWithCoder:(NSCoder* ) aDeCoder; * * * - (void) encodeWithCoder:(NSCoder* ) aCoder { [aCoder encodeObject: name forKey:@"personName"]; [aCoder encodeInt: id forKey:@"personId"]; } - (void) initWithCoder:(NSCoder* ) aDeCoder { self = [super init]; if(self) { name = [aDecoder decodeObjectForKey:@"personName"]; id = [aDecoder decodeIntForKey:@"personId"]; } return self; }
  • 8. About  Applica@on  Sandbox   •  Every  iOS  app  has  its  own  applica@on  sandbox   •  Sandbox  is  a  directory  on  the  filesystem  that  is  barricaded   from  the  rest  of  the  file  system   •  Sandbox  directory  structure   –  Library/Preferences   •  Preferences  files.  Backed  up.   –  Tmp/   •  Temp  data  storage  on  run@me.  NSTemporaryDirectory  will  give  you  a   path  to  this  dir   –  Documents/   •  Write  data  for  permanent  storage.  Backed  up.   –  Library/Caches   •  Same  than  Documents  except  it’s  not  backed  up.  Example:  fetch  large   data  from  web  server  and  store  it  here.  
  • 9. Archiving  to  Documents/  dir   // Searches file system for a path that meets the criteria given by the // arguments. On iOS the last two arguments are always the same! (Mac OS X has several // more options) // // Returns array of strings, in iOS only one string in the array. NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserFomainMask, YES); // Fetch the only document directory found in the array NSString *documentDirectory = [documentDirectories objectAtIndex:0]; // Add file name to the end of the array NSString *path = [documentDirectory stringByAppendingPathComponent:@"file.archive"];
  • 10. NSKeyedArchiver  and   NSKeyedUnarchiver   •  NSKeyedArchiver  provides  a  way  to  encode   objects  into  a  file.   [NSKeyedArchiver archiveRootObject: someObject toFile: path]; •  NSKeyedUnarchiver  decodes  the  objects  from   file   someObject = [NSKeyedUnArchiver unarchiveObjectWithFile: path];
  • 11. Reading  and  Wri@ng  Files   •  NSData  and  NSString  provides  easy  access  for   reading  and  wri@ng  bytes.     •  NSDic@onary  has  also  methods  for  saving  and   storing  the  dic@onary  to  property  list  (xml  file)   •  Also  standard  file  I/O  func@ons  from  C  library   available   –  fopen,  fread,  fwrite    
  • 12. Wri@ng  to  File  System  using  NSData   •  NSData  provides  convinient  methods  for   reading  and  wri@ng  to  file  system   –  - writeToFile:atomically –  + dataWithContentsOfFile •  Example   –  [someData writeToFile:path atomically:YES] –  NSData* data = [NSData dataWithContestOfFile: path];