Tworzenie zaawansowanych aplikacji w środowisku ios Wykład 7 Saving data in ios
Agenda NSString and NSData NSFileManager Property List JSON Core Data
ios Directories App Documents Inbox Library Caches temp
ios Directories Directory Description Backed up by itunes AppName.app This directory contains the app and all of its resources. NO Documents/ Use this directory to store user-generated content. YES Documents/Inbox Use this directory to access files that your app was asked to open by outside entities. Such as mail s attachments. YES Library This is the top-level directory for any files that are not user data files. YES Library/Caches Subfolder of Library for any caching files. NO Tmp/ Use this directory to write temporary files that don t need to persist between launches of your app. NO
Accessing File Paths NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString *docpath = [paths firstobject]; NSString *path = [docpath stringbyappendingcomponent:@ myfile.txt ];
Writing NSData BOOL success = [data writetofile:path options:nsdatawritingatomic error:&error]; NSDataWritingAtomic - create temp file first NSDataWritingWithoutOverwriting - prevent overwriting an existing file
Reading NSData [NSData alloc] initwithcontentsoffile: path options:nsdatareadingmappedifsafe error:&error]; NSDataReadingMappedIfSafe - file should be mapped into virtual memory, if possible and safe NSDataReadingUncached - file should not be stored in the file-system caches NSDataReadingMappedAlways - map the file, if possible.
Writing NSString BOOL success = [mystring writetofile:path atomically:yes encoding:nsutf8stringencoding error:&error]; NSUTF8StringEncoding - 8-bit representation of Unicode characters NSASCIIStringEncoding - Strict 7-bit ASCII encoding within 8-bit chars.
Reading NSString [NSData alloc] initwithcontentsoffile:path encoding:nsutf8stringencoding error:&error];
Writing/Reading NSString and NSData DEMO
NSFileManager NSFileManager *filemanager = [NSFileManager defaultmanager]; Providing a convenient way to: create read move copy delete files and directories.
NSFileManager NSFileManager *filemanager = [NSFileManager defaultmanager]; NSString *documentspath = [NSSearchPathForDirectoriesInDomains(NSDocumentDir ectory, NSUserDomainMask, YES) firstobject]; NSString *filepath = [documentspath stringbyappendingpathcomponent:@"file.txt"]; BOOL fileexists = [filemanager fileexistsatpath:filepath];
NSFileManager - list of files NSFileManager *filemanager = [NSFileManager defaultmanager]; NSArray *urls = [filemanager URLsForDirectory:NSDocumentDirectory indomains:nsuserdomainmask]; NSArray *files = [filemanager contentsofdirectoryaturl: [urls firstobject] includingpropertiesforkeys:nil options:nsdirectoryenumerationskipshiddenfiles error:&error];
NSFileManager - list of files [filemanager contentsofdirectoryaturl:[urls firstobject] includingpropertiesforkeys:nil options:nsfilebusy error:&error]; NSFileAppendOnly - The key in a file attribute dictionary whose value indicates whether the file is read-only. NSFileBusy - The key in a file attribute dictionary whose value indicates whether the file is busy. NSFileCreationDate - The key in a file attribute dictionary whose value indicates the file's creation date NSFileType - The key in a file attribute dictionary whose value indicates the file's type. NSDirectoryEnumerationSkipsHiddenFiles - Do not enumerate hidden files....
NSFileManager - list of files NSPredicate *predicate = [NSPredicate predicatewithformat:@"pathextension == 'png'"]; for (NSURL *fileurl in [contents filteredarrayusingpredicate:predicate]) { // Enumerate each.png file in directory }
NSFileManager - create/delete directory NSFileManager *filemanager = [NSFileManager defaultmanager]; NSString *documentspath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstobject]; NSString *imagespath = [documentspath stringbyappendingpathcomponent:@"images"]; if (![filemanager fileexistsatpath:imagespath]) { [filemanager createdirectoryatpath:imagespath withintermediatedirectories:no attributes:nil error:nil]; } BOOL deletesucess = [filemanager removeitematpath:imagespath error:&error];
NSFileManager - copy/move directory BOOL success = [filemanager moveitematpath:source topath:destination error:&error]; BOOL success = [filemanager copyitematurl:source tourl:destination error:&error];
NSFileManager DEMO
Property List
Property List XML Property List Standard Property List Editable by hand Device Independent Binary Property List Fast loading ASCII Legacy Property List Read only
Property List - supported types Abstract type XML element Cocoa class Core Foundation type array <array> NSArray CFArray dictionary <dict> NSDictionary CFDictionary string <string> NSString CFString data <data> NSData CFData date <date> NSDate CFDate number - integer <integer> NSNumber (intvalue) CFNumber number - floating point <real> NSNumber (floatvalue) CFNumber Boolean <true/> or <false/> NSNumber (boolvalue == YES or boolvalue == NO) CGBoolean
Property List - reading [NSPropertyListSerialization propertylistwithdata:data options:nspropertylistimmutable format:&format error:&error]; NSPropertyListImmutable - Specifies that the property list should be immutable. NSPropertyListMutableContainers - Causes the returned property list to have mutable containers but immutable leaves. NSPropertyListMutableContainersAndLeaves - Causes the returned property list to have mutable containers and leaves.
Property List - reading [NSPropertyListSerialization propertylistwithdata:data options:nspropertylistimmutable format:&format error:&error]; NSPropertyListOpenStepFormat - Specifies the ASCII property list format inherited from the OpenStep APIs. NSPropertyListXMLFormat_v1_0 - Specifies the XML property list format. NSPropertyListBinaryFormat_v1_0 - Specifies the binary property list format.
Property List - writing [NSPropertyListSerialization datawithpropertylist:plist format:nspropertylistxmlformat_v1_0 options:0 error:&error]; Property list must have one object as the root object. The option parameter is currently unused. Unsupported types will fail with an error.
Property List DEMO
JSON JSON stands for JavaScript Object Notation. It is a human readable format used to transmit data. JSON is formatted in attribute-value pairs. It is an alternative to XML for sending data across the network.
JSON - types Primitive JavaScript Types: String, Boolean, Number, Null Arrays are indicated by brackets - [] Objects are indicated by braces - {} Objects are collection of name-value pairs. Use commas to add additional fields.
JSON - NSJSONSerialization Convert JSON to foundation objects or can convert foundation to JSON The top level object is an NSArray or an NSDictionary All objects are insentence of NSString, NSNumber, NSArray, NSDictionary or NSNull All dictionary keys are NSString
JSON - Decoding +JSONObjectWithData:options:error: +JSONObjectWithStream:options:error:
JSON - Encoding +datawithjsonobject:options:error +writejsonobject:tostream:options:error
JSON DEMO
Core Data Managed Object Context Presistent Store Managed Objects Modeling Objects Fetch Request