SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Downloaden Sie, um offline zu lesen
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];

Weitere ähnliche Inhalte

Was ist angesagt?

Building a userspace filesystem in node.js
Building a userspace filesystem in node.jsBuilding a userspace filesystem in node.js
Building a userspace filesystem in node.jsClay Smith
 
(No)SQL Timing Attacks for Data Retrieval
(No)SQL Timing Attacks for Data Retrieval(No)SQL Timing Attacks for Data Retrieval
(No)SQL Timing Attacks for Data RetrievalPositive Hack Days
 
A New MongoDB Sharding Architecture for Higher Availability and Better Resour...
A New MongoDB Sharding Architecture for Higher Availability and Better Resour...A New MongoDB Sharding Architecture for Higher Availability and Better Resour...
A New MongoDB Sharding Architecture for Higher Availability and Better Resour...leifwalsh
 
Saving Data
Saving DataSaving Data
Saving DataSV.CO
 
Шардинг в MongoDB, Henrik Ingo (MongoDB)
Шардинг в MongoDB, Henrik Ingo (MongoDB)Шардинг в MongoDB, Henrik Ingo (MongoDB)
Шардинг в MongoDB, Henrik Ingo (MongoDB)Ontico
 
04 data accesstechnologies
04 data accesstechnologies04 data accesstechnologies
04 data accesstechnologiesBat Programmer
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applicationsjeromevdl
 
Terraform, Ansible or pure CloudFormation
Terraform, Ansible or pure CloudFormationTerraform, Ansible or pure CloudFormation
Terraform, Ansible or pure CloudFormationgeekQ
 
BITS: Introduction to relational databases and MySQL - Schema design
BITS: Introduction to relational databases and MySQL - Schema designBITS: Introduction to relational databases and MySQL - Schema design
BITS: Introduction to relational databases and MySQL - Schema designBITS
 
Terraform, Ansible, or pure CloudFormation?
Terraform, Ansible, or pure CloudFormation?Terraform, Ansible, or pure CloudFormation?
Terraform, Ansible, or pure CloudFormation?geekQ
 
Lucene InputFormat (lightning talk) - TriHUG December 10, 2013
Lucene InputFormat (lightning talk) - TriHUG December 10, 2013Lucene InputFormat (lightning talk) - TriHUG December 10, 2013
Lucene InputFormat (lightning talk) - TriHUG December 10, 2013mumrah
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of SlickKnoldus Inc.
 
Web scraping with nutch solr part 2
Web scraping with nutch solr part 2Web scraping with nutch solr part 2
Web scraping with nutch solr part 2Mike Frampton
 
Puppet overview
Puppet overviewPuppet overview
Puppet overviewMike_Foto
 
Introduce leo-redundant-manager
Introduce leo-redundant-managerIntroduce leo-redundant-manager
Introduce leo-redundant-managerParas Patel
 

Was ist angesagt? (20)

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

Andere mochten auch

Andere mochten auch (7)

Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 
Expanding Programming Skills (C++): Intro to Course
Expanding Programming Skills (C++): Intro to CourseExpanding Programming Skills (C++): Intro to Course
Expanding Programming Skills (C++): Intro to Course
 
iOS Selectors Blocks and Delegation
iOS Selectors Blocks and DelegationiOS Selectors Blocks and Delegation
iOS Selectors Blocks and Delegation
 
Compiling Qt Apps
Compiling Qt AppsCompiling Qt Apps
Compiling Qt Apps
 
Intro to Java Technology
Intro to Java TechnologyIntro to Java Technology
Intro to Java Technology
 
Android Sensors
Android SensorsAndroid Sensors
Android Sensors
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 

Ähnlich wie iOS: Using persistant storage

Ts archiving
Ts   archivingTs   archiving
Ts archivingConfiz
 
Connecting to a REST API in iOS
Connecting to a REST API in iOSConnecting to a REST API in iOS
Connecting to a REST API in iOSgillygize
 
The Role of Atom/AtomPub in Digital Archive Services at The University of Tex...
The Role of Atom/AtomPub in Digital Archive Services at The University of Tex...The Role of Atom/AtomPub in Digital Archive Services at The University of Tex...
The Role of Atom/AtomPub in Digital Archive Services at The University of Tex...Peter Keane
 
09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WPNguyen Tuan
 
Oracle forensics 101
Oracle forensics 101Oracle forensics 101
Oracle forensics 101fangjiafu
 
Hibernate in XPages
Hibernate in XPagesHibernate in XPages
Hibernate in XPagesToby Samples
 
Information Retrieval - Data Science Bootcamp
Information Retrieval - Data Science BootcampInformation Retrieval - Data Science Bootcamp
Information Retrieval - Data Science BootcampKais Hassan, PhD
 
React Native Course - Data Storage . pdf
React Native Course - Data Storage . pdfReact Native Course - Data Storage . pdf
React Native Course - Data Storage . pdfAlvianZachryFaturrah
 
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...smn-automate
 
Using Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowUsing Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowKarsten Dambekalns
 
INT 222.pptx
INT 222.pptxINT 222.pptx
INT 222.pptxSaunya2
 
14 file handling
14 file handling14 file handling
14 file handlingAPU
 
iOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataiOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataChris Mar
 
Elastic Search
Elastic SearchElastic Search
Elastic SearchNavule Rao
 
Development of the irods rados plugin @ iRODS User group meeting 2014
Development of the irods rados plugin @ iRODS User group meeting 2014Development of the irods rados plugin @ iRODS User group meeting 2014
Development of the irods rados plugin @ iRODS User group meeting 2014mgrawinkel
 
From SQL to MongoDB
From SQL to MongoDBFrom SQL to MongoDB
From SQL to MongoDBNuxeo
 
BlueStore: a new, faster storage backend for Ceph
BlueStore: a new, faster storage backend for CephBlueStore: a new, faster storage backend for Ceph
BlueStore: a new, faster storage backend for CephSage Weil
 
Ceph Tech Talk: Bluestore
Ceph Tech Talk: BluestoreCeph Tech Talk: Bluestore
Ceph Tech Talk: BluestoreCeph Community
 
Skillwise - Enhancing dotnet app
Skillwise - Enhancing dotnet appSkillwise - Enhancing dotnet app
Skillwise - Enhancing dotnet appSkillwise Group
 

Ähnlich wie iOS: Using persistant storage (20)

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

Mehr von Jussi Pohjolainen

libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferencesJussi Pohjolainen
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationJussi Pohjolainen
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDXJussi Pohjolainen
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript DevelopmentJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDXJussi Pohjolainen
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDXJussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesJussi Pohjolainen
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platformJussi Pohjolainen
 
Intro to Java ME and Asha Platform
Intro to Java ME and Asha PlatformIntro to Java ME and Asha Platform
Intro to Java ME and Asha PlatformJussi Pohjolainen
 

Mehr von Jussi Pohjolainen (20)

Moved to Speakerdeck
Moved to SpeakerdeckMoved to Speakerdeck
Moved to Speakerdeck
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
Box2D and libGDX
Box2D and libGDXBox2D and libGDX
Box2D and libGDX
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
 
libGDX: Tiled Maps
libGDX: Tiled MapslibGDX: Tiled Maps
libGDX: Tiled Maps
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
libGDX: Scene2D
libGDX: Scene2DlibGDX: Scene2D
libGDX: Scene2D
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: User Input
libGDX: User InputlibGDX: User Input
libGDX: User Input
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
Intro to Java ME and Asha Platform
Intro to Java ME and Asha PlatformIntro to Java ME and Asha Platform
Intro to Java ME and Asha Platform
 
Intro to PhoneGap
Intro to PhoneGapIntro to PhoneGap
Intro to PhoneGap
 

Kürzlich hochgeladen

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Kürzlich hochgeladen (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

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];