Files & Archiving. Lecture 8

Similar documents
Stanford CS193p. Developing Applications for ios. Fall Stanford CS193p. Fall 2011

Review. Objective-C Classes, Methods, Properties, Protocols, Delegation, Memory Management

ITP 342 Mobile App Development. Data Persistence

ITP 342 Mobile App Development. Data Persistence

Life Cycle. Chapter Explore the Game Application. Understanding the Views in a Game

COSC$4355/6355$ $Introduction$to$Ubiquitous$Computing$ Exercise$3$ September!17,!2015!

CS193E Lecture 7. Document-based Applications NSTableView Key-Value Coding

Stanford CS193p. Developing Applications for ios. Spring Stanford CS193p. Spring 2012

Mobile Application Development L12: Storage & Communication

Developing Applications for ios

ITP 342 Advanced Mobile App Dev. Core Data

COMP327 Mobile Computing Session: Lecture Set 4 - Data Persistence, Core Data and Concurrency

NSObject. - (NSString *)description Provides us with a string description of the object

Cocoa, Objective C - Alert Panels!

Mobile Application Programming. Data and Persistence

CS193E Lecture #3 Categories and Protocols Cocoa Memory Management

Mobile Application Programming. Data and Persistence

Praktikum Entwicklung von Mediensystemen mit ios

Data Management: Data Types & Collections

Object-Oriented Programming with Objective-C. Lecture 2

Getting Help. iphone Application Programming Lecture 3: Foundation Classes. Data Structures in Objective C. Online Documentation.

CSCI 251: iphone Application Development

iphone Application Programming Lecture 3: Foundation Classes

Collections & Memory Management. Lecture 2

Lab #1: Chuck Norris Joke Generator Class

About MSDOSX. Lecture 0

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar

InterfaceBuilder and user interfaces

Persistence. CS 442: Mobile App Development Michael Saelee

Data Management

CS193p Spring 2010 Thursday, April 29, 2010

Mobile Application Development

Cross Platform Nearby Networking

COCOA WORKSHOP PART 1. Andreas Monitzer

Stanford CS193p. Developing Applications for ios. Fall Stanford CS193p. Fall 2011

App SandBox Directory

iphone OS Overview

From Hello World to Finished App. raywenderlich.com

Getting Help. iphone Application Programming Lecture 3: Foundation Classes. Data Structures in Objective C. Online Documentation.

CS193P - Lecture 3. iphone Application Development. Custom Classes Object Lifecycle Autorelease Properties

Advanced ios. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 20 11/01/2012

Data IAP 2010 iphonedev.csail.mit.edu edward benson / Thursday, January 14, 2010

Announcement. Final Project Proposal Presentations and Updates

Data Storage. Dr. Sarah Abraham

Design Phase. Create a class Person. Determine the superclass. NSObject (in this case)

Objective-C and COCOA Applications

Core Animation. Building Animated UI s. Bill Dudney. Gala Factory Software LLC. Bill Dudney Core Animation: Building Animated UI s Slide 1

Advanced Memory Analysis with Instruments. Daniel Delwood Performance Tools Engineer

Bindings Example Exercise James Dempsey - WWDC Pre-Show Cocoa Workshop

ITP 342 Advanced Mobile App Dev. Memory

Mobile Application Development

Covers ios 6. Bear Cahill. Includes 98 Techniques MANNING

Cocoa and Objective-C Cookbook

AsyncNetwork Cocoa & ios Networking Evolved

CS 47. Beginning iphone Application Development

CS193E Lecture 12. Formatters Cocoa Text More View Drawing

Abstract Data Types. 2501ICT/7421ICTNathan. René Hexel. Semester 1, School of Information and Communication Technology Griffith University

A Mobile Mapping Application

Review. iphone Application Programming Lecture 2: Objective-C, Cocoa. History. Objective-C. Device restrictions. Interaction paradigm changes

Code Examples. C# demo projects. PHP Rest Client

CS193E Lecture 11. Copy/Paste & Pasteboards Scrolling Printing

Contents. iphone Training. Industry Trainers. Classroom Training Online Training ON-DEMAND Training. Read what you need

Lab #1: Chuck Norris Joke Generator Class

Review. iphone Application Programming Lecture 2: Objective-C, Cocoa. History. Objective-C. Device restrictions. Interaction paradigm changes

Cocoa Development Tips

ios Development Lecture 1 Introduction to Objective-C Ing. Simone Cirani

Principles of Programming Languages. Objective-C. Joris Kluivers

Advanced Performance Optimization on iphone OS

Stanford CS193p. Developing Applications for iphone 4, ipod Touch, & ipad Spring Stanford CS193p Spring 2011

Praktikum Entwicklung von Mediensystemen mit ios

Collections. Fall, Prof. Massimiliano "Max" Pala

File System Programming Guide

DL/ID Parsing Component for ios

Developing Applications for ios

Saving Data in ios Hands-On Challenges

Objective-C ICT/7421ICTNathan. René Hexel. School of Information and Communication Technology Griffith University.

Concepts in Objective-C Programming

What s New in Cocoa for macos

For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to

ITP 342 Mobile App Development. Singleton

Developing applications for ios

AVAudioRecorder & System Sound Services

Data Storage. Mobile Application Development in ios School of EECS Washington State University Instructor: Larry Holder

COMP327 Mobile Computing Session:

Advanced Object- C Features

Agenda. Core Data! Next Week! Storing your Model permanently in an object-oriented database.! Multitasking! Advanced Segueing! Map Kit?

CS193P - Lecture 2. iphone Application Development. Objective-C Foundation Framework

Objective-C Runtime. Cocoa s Jewel in the Crown. NSConference Nicolas

Objective-C Primer. iphone Programmer s Association. Lorenzo Swank September 10, 2008

Stanford CS193p. Developing Applications for ios. Fall Stanford CS193p. Fall 2011

E Event-based parser, XML, 180 Extended attributes, URLs, 118 API, 119 command line, 118 description, 118 NSURL category, 119

OVERVIEW. Why learn ios programming? Share first-hand experience. Identify platform differences. Identify similarities with.net

Stanford CS193p. Developing Applications for ios Fall Stanford CS193p. Fall 2013

CS193E Lecture 16. Internationalization and Localization

Assignment II: Foundation Calculator

SQLitePersistentObjects

Objective-C Part 2 (ECS189H) Ken Joy Serban Porumbescu

Mobile Application Programming. Memory Management

Announcements. Today s Topics

IPHONE DEVELOPMENT. Getting Started with the iphone SDK

Transcription:

Files & Archiving Lecture 8

Persistent Data

NSUserDefaults Dead simple to use Just one big file Only supports property list types What if you want more features?

File Tasks Finding the file path User selected Internal application data Saving or loading file data Text files, property lists, custom objects

Finding the File NSOpenPanel

Finding the File NSOpenPanel NSOpenPanel *panel = [NSOpenPanel openpanel]; [panel beginsheetfordirectory:nil file:nil types:[nsarray arraywithobject:@"jpg"] modalforwindow:window modaldelegate:self didendselector:@selector(openpaneldidend:returncode:contextinfo:) contextinfo:null]; - (void)openpaneldidend:(nssavepanel *)sheet { } returncode:(int)returncode contextinfo:(void *)contextinfo if (returncode == NSOKButton) [self openfrompath:[sheet filename]];

Finding the File NSSavePanel

Finding the File NSSavePanel NSSavePanel *panel = [NSSavePanel savepanel]; [panel setallowedfiletypes:[nsarray arraywithobject:@"txt"]]; [panel beginsheetfordirectory:nil file:nil modalforwindow:window modaldelegate:self didendselector:@selector(savepaneldidend:returncode:contextinfo:) contextinfo:null]; - (void)savepaneldidend:(nssavepanel *)sheet { } returncode:(int)returncode contextinfo:(void *)contextinfo if (returncode == NSOKButton) [self savetopath:[sheet filename]];

Finding the File Application Support Any other files associated with your application should go in ~/Library/ Application Support/YourApp Use the C function NSSearchPathForDirectoriesInDomains to find it Use NSFileManager to create your subdirectory

NSFileManager Creates, deletes, and moves files and directories Sets attributes and makes symbolic links Supports iterating through the files in a directory with contentsofdirectoryatpath:error:

Application Support & NSFileManager NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); if ([paths count] == 0) { // handle error } NSString *applicationsupport = [paths objectatindex:0]; NSString *appdir = [applicationsupport stringbyappendingpathcomponent:@"myappname"]; if (![[NSFileManager defaultmanager] fileexistsatpath:appdir]) [[NSFileManager defaultmanager] createdirectoryatpath:appdir attributes:nil];

NSDocument Used to create document-based applications Handles saving and loading, undo, printing, and some window management

Saving & Loading File Data

Text Files To initialize from a file, [[NSString alloc] initwithcontentsoffile:@"/a/b.txt" encoding:nsutf8stringencoding error:&error] To save to a file, [string writetofile:@"/a/b.txt" atomically:yes encoding:enc error:&error]

Collections of Property List Objects If you have an NSArray or NSDictionary of property list objects (instances of NSData, NSDate, NSNumber, NSString, NSArray, or NSDictionary), you can use writetofile:atomically: and initwithcontentsoffile: to easily read and write the collection See also: NSPropertyListSerialization

Other Classes Various other classes support saving and loading Look for initwithcontentsoffile: and writetofile: methods Some classes (NSImage, for example) use NSData for saving and loading

Reading NSData Represents a chunk of binary data Load from a file with initwithcontentsoffile:@"/a/b.txt" Load from a URL with initwithcontentsofurl:[nsurl URLWithString:@"http://google.com/"] Load from a C array with initwithbytes:arr length:len

Loading NSData Many Cocoa classes support loading from NSData Images [[NSImage alloc] initwithdata:data] Sounds [[NSSound alloc] initwithdata:data] PDFs [[PDFDocument alloc] initwithdata:data]

Generating NSData Many Cocoa classes can also be turned into NSData Attributed text to RTF data [attributedstring RTFFromRange:attributes:] PDF documents [pdfdocument datarepresentation] Images [image TIFFRepresentation]

Writing NSData Once you have an NSData object, you can write it to a file with [data writetofile:@"/a/b.ext" atomically:yes] NSData objects are also property list objects, meaning you can read and write them using NSUserDefaults, NSDictionary, or NSArray

What about custom objects?

NSCoding NSCoding is a protocol your class can implement to enable archiving and unarchiving A protocol specifies a set of methods your class must implement Theyʼre like Java interfaces, if youʼve seen those

NSCoding @interface MyObject : NSObject <NSCoding> { NSString *name; int age; } @property(nonatomic, retain) NSString *name; @property(nonatomic) int age; - (id)initwithname:(nsstring *)name age:(int)age; - (id)initwithcoder:(nscoder *)coder; - (void)encodewithcoder:(nscoder *)coder; @end

encodewithcoder: For each variable you want to save, call [coder encodetype:var forkey:@"key"] Each object you encode with encodeobject:forkey: must implement NSCoding as well If the superclass implements NSCoding, call [super encodewithcoder:coder]

encodewithcoder: - (void)encodewithcoder:(nscoder *)coder { [coder encodeobject:author forkey:@"author"]; [coder encodeobject:title forkey:@"title"]; [coder encodeobject:chapters forkey:@"chapters"]; [coder encodeint:callnumber forkey:@"callnumber"]; } An encodewithcoder: implementation for a Book class

initwithcoder: The inverse of encodewithcoder: for each encoded key, call [coder decodetypeforkey:@"key"] If itʼs an object, remember to retain it This is still an init method donʼt forget [super init] and return self

initwithcoder: - (id)initwithcoder:(nscoder *)coder { if (![super init]) { return nil; } author = [[coder decodeobjectforkey:@"author"] retain]; title = [[coder decodeobjectforkey:@"title"] retain]; chapters = [[coder decodeobjectforkey:@"chapters"] retain]; callnumber = [coder decodeintforkey:@"callnumber"]; return self; } An initwithcoder: implementation for the same Book class

Saving and Loading NSCoding Objects

NSKeyedArchiver & NSKeyedUnarchiver Handles reading and writing (to files or NSData) for NSCoding objects NSKeyedArchiver archiveddatawithrootobject: archiverootobject:tofile: NSKeyedUnarchiver unarchiveobjectwithdata: unarchiveobjectwithfile:

NSKeyedArchiver & NSKeyedUnarchiver MyObject *x = [[MyObject alloc] init], *y; NSString *f = @"/Path/to/file.ext"; [NSKeyedArchiver archiverootobject:x tofile:f]; y = [NSKeyedUnarchiver unarchiveobjectwithfile:f]; // x and y should now have the same data