SlideShare a Scribd company logo
1 of 166
Download to read offline
CS193P - Lecture 9
        iPhone Application Development

        Data in Your iPhone App
        Chris Marcellino




Tuesday, February 2, 2010                1
Today’s Topics
        • Data in Your iPhone App
            ■ Saving & loading local data
            ■ Accessing remote data over the Internet




Tuesday, February 2, 2010                               2
Today’s Topics
        • Property Lists, NSUserDefaults and Settings
        • iPhone’s File System
        • Archiving Objects
        • The Joy of SQLite
        • JSON
        • Apple Push Notification Service




Tuesday, February 2, 2010                               3
Property Lists




Tuesday, February 2, 2010   4
Property Lists
        • Convenient way to store a small amount of data
            ■ Arrays, dictionaries, strings, numbers, dates, raw data
            ■ Human-readable XML or binary format


        • NSUserDefaults class uses property lists under the hood




Tuesday, February 2, 2010                                               5
When Not to Use Property Lists
        • More than a few hundred KB of data
            ■   Loading a property list is all-or-nothing
        • Complex object graphs
        • Custom object types
        • Multiple writers (e.g. not ACID)




Tuesday, February 2, 2010                                   6
Reading & Writing Property Lists
        • NSArray and NSDictionary convenience methods
        • Operate recursively
           // Writing
           - (BOOL)writeToFile:(NSString *)aPath atomically:(BOOL)flag;
           - (BOOL)writeToURL:(NSURL *)aURL atomically:(BOOL)flag;

           // Reading
           - (id)initWithContentsOfFile:(NSString *)aPath;
           - (id)initWithContentsOfURL:(NSURL *)aURL;




Tuesday, February 2, 2010                                                 7
Writing an Array to Disk




Tuesday, February 2, 2010          8
Writing an Array to Disk
        NSArray *array = [NSArray arrayWithObjects:@“Foo”,




Tuesday, February 2, 2010                                    8
Writing an Array to Disk
        NSArray *array = [NSArray arrayWithObjects:@“Foo”,
                          [NSNumber numberWithBool:YES],




Tuesday, February 2, 2010                                    8
Writing an Array to Disk
        NSArray *array = [NSArray arrayWithObjects:@“Foo”,
                          [NSNumber numberWithBool:YES],
                          [NSDate dateWithTimeIntervalSinceNow:60],




Tuesday, February 2, 2010                                             8
Writing an Array to Disk
        NSArray *array = [NSArray arrayWithObjects:@“Foo”,
                          [NSNumber numberWithBool:YES],
                          [NSDate dateWithTimeIntervalSinceNow:60],
                          nil];




Tuesday, February 2, 2010                                             8
Writing an Array to Disk
        NSArray *array = [NSArray arrayWithObjects:@“Foo”,
                          [NSNumber numberWithBool:YES],
                          [NSDate dateWithTimeIntervalSinceNow:60],
                          nil];
        [array writeToFile:@“MyArray.plist” atomically:YES];




Tuesday, February 2, 2010                                             8
Writing an Array to Disk
        NSArray *array = [NSArray arrayWithObjects:@“Foo”,
                          [NSNumber numberWithBool:YES],
                          [NSDate dateWithTimeIntervalSinceNow:60],
                          nil];
        [array writeToFile:@“MyArray.plist” atomically:YES];


               <?xml version="1.0" encoding="UTF-8"?>
               <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
               "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
               <plist version="1.0">
               <array>
                	    <string>Foo</string>
                	    <true/>
                	    <date>2010-02-02T09:26:18Z</date>
               </array>
               </plist>



Tuesday, February 2, 2010                                             8
Writing a Dictionary to Disk




Tuesday, February 2, 2010              9
Writing a Dictionary to Disk
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:




Tuesday, February 2, 2010                                                  9
Writing a Dictionary to Disk
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              @“Bob”, @“Name”,




Tuesday, February 2, 2010                                                  9
Writing a Dictionary to Disk
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              @“Bob”, @“Name”,
                              [NSNumber numberWithInt:9], @“Lecture”,




Tuesday, February 2, 2010                                                  9
Writing a Dictionary to Disk
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              @“Bob”, @“Name”,
                              [NSNumber numberWithInt:9], @“Lecture”,
                              nil];




Tuesday, February 2, 2010                                                  9
Writing a Dictionary to Disk
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              @“Bob”, @“Name”,
                              [NSNumber numberWithInt:9], @“Lecture”,
                              nil];
        [dict writeToFile:@“MyDict.plist” atomically:YES];




Tuesday, February 2, 2010                                                  9
Writing a Dictionary to Disk
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              @“Bob”, @“Name”,
                              [NSNumber numberWithInt:9], @“Lecture”,
                              nil];
        [dict writeToFile:@“MyDict.plist” atomically:YES];


               <?xml version="1.0" encoding="UTF-8"?>
               <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
               "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
               <plist version="1.0">
               <dict>
                	    <key>Name</key>
                	    <string>Bob</string>
                	    <key>Lecture</key>
                	    <integer>10</integer>
               </dict>
               </plist>


Tuesday, February 2, 2010                                                  9
NSPropertyListSerialization
        • Allows finer-grained control
            ■ File format
            ■ More descriptive errors

            ■ Mutability




Tuesday, February 2, 2010                10
NSPropertyListSerialization
        • Allows finer-grained control
            ■ File format
            ■ More descriptive errors

            ■ Mutability



        // Property list to NSData
        + (NSData *)dataFromPropertyList:(id)plist
                                   format:(NSPropertyListFormat)format
                        errorDescription:(NSString **)errorString;

        // NSData to property list
        + (id)propertyListFromData:(NSData *)data
                  mutabilityOption:(NSPropertyListMutabilityOptions)opt
                            format:(NSPropertyListFormat *)format
                  errorDescription:(NSString **)errorString;




Tuesday, February 2, 2010                                                 10
More on Property Lists
        • “Property List Programming Guide for Cocoa”
          http://developer.apple.com/documentation/Cocoa/
          Conceptual/PropertyLists/




Tuesday, February 2, 2010                                   11
iPhone’s File System




Tuesday, February 2, 2010      12
Keeping Applications Separate




                                      Image (cc) by davidsilver on Flickr




Tuesday, February 2, 2010                                                   13
Why Keep Applications Separate?
        • Security
        • Privacy
        • Cleanup after deleting an app




Tuesday, February 2, 2010                 14
Home Directory Layout




Tuesday, February 2, 2010       15
Home Directory Layout
        • Each app has its own set of directories




Tuesday, February 2, 2010                           15
Home Directory Layout
        • Each app has its own set of directories
        • <Application Home>




Tuesday, February 2, 2010                           15
Home Directory Layout
        • Each app has its own set of directories
        • <Application Home>
            ■   MyApp.app




Tuesday, February 2, 2010                           15
Home Directory Layout
        • Each app has its own set of directories
        • <Application Home>
            ■   MyApp.app
                 ■   MyApp




Tuesday, February 2, 2010                           15
Home Directory Layout
        • Each app has its own set of directories
        • <Application Home>
            ■   MyApp.app
                 ■ MyApp
                 ■ MainWindow.nib




Tuesday, February 2, 2010                           15
Home Directory Layout
        • Each app has its own set of directories
        • <Application Home>
            ■   MyApp.app
                 ■ MyApp
                 ■ MainWindow.nib

                 ■ SomeImage.png




Tuesday, February 2, 2010                           15
Home Directory Layout
        • Each app has its own set of directories
        • <Application Home>
            ■   MyApp.app
                 ■ MyApp
                 ■ MainWindow.nib

                 ■ SomeImage.png

            ■   Documents




Tuesday, February 2, 2010                           15
Home Directory Layout
        • Each app has its own set of directories
        • <Application Home>
            ■   MyApp.app
                 ■ MyApp
                 ■ MainWindow.nib

                 ■ SomeImage.png

            ■ Documents
            ■ Library




Tuesday, February 2, 2010                           15
Home Directory Layout
        • Each app has its own set of directories
        • <Application Home>
            ■   MyApp.app
                 ■ MyApp
                 ■ MainWindow.nib

                 ■ SomeImage.png

            ■ Documents
            ■ Library

                 ■   Caches




Tuesday, February 2, 2010                           15
Home Directory Layout
        • Each app has its own set of directories
        • <Application Home>
            ■   MyApp.app
                 ■ MyApp
                 ■ MainWindow.nib

                 ■ SomeImage.png

            ■ Documents
            ■ Library

                 ■ Caches
                 ■ Preferences




Tuesday, February 2, 2010                           15
Home Directory Layout
        • Each app has its own set of directories
        • <Application Home>
            ■   MyApp.app
                 ■ MyApp
                 ■ MainWindow.nib

                 ■ SomeImage.png

            ■ Documents
            ■ Library

                 ■ Caches
                 ■ Preferences


        • Applications only read and write within their home directory


Tuesday, February 2, 2010                                                15
Home Directory Layout
        • Each app has its own set of directories
        • <Application Home>
            ■   MyApp.app
                 ■ MyApp
                 ■ MainWindow.nib

                 ■ SomeImage.png

            ■ Documents
            ■ Library

                 ■ Caches
                 ■ Preferences


        • Applications only read and write within their home directory
        • Backed up by iTunes during sync (mostly)

Tuesday, February 2, 2010                                                15
File Paths in Your Application




Tuesday, February 2, 2010                16
File Paths in Your Application
         // Basic directories
         NSString *homePath = NSHomeDirectory();
         NSString *tmpPath = NSTemporaryDirectory();




Tuesday, February 2, 2010                              16
File Paths in Your Application
         // Basic directories
         NSString *homePath = NSHomeDirectory();
         NSString *tmpPath = NSTemporaryDirectory();

         // Documents directory
         NSArray *paths = NSSearchPathForDirectoriesInDomains
                          (NSDocumentDirectory, NSUserDomainMask, YES);
         NSString *documentsPath = [paths objectAtIndex:0];




Tuesday, February 2, 2010                                                 16
File Paths in Your Application
         // Basic directories
         NSString *homePath = NSHomeDirectory();
         NSString *tmpPath = NSTemporaryDirectory();

         // Documents directory
         NSArray *paths = NSSearchPathForDirectoriesInDomains
                          (NSDocumentDirectory, NSUserDomainMask, YES);
         NSString *documentsPath = [paths objectAtIndex:0];



         // <Application Home>/Documents/foo.plist
         NSString *fooPath =
         [documentsPath stringByAppendingPathComponent:@“foo.plist”];




Tuesday, February 2, 2010                                                 16
Including Writable Files with Your App
        • Many applications want to include some starter data
        • But application bundles are code signed
            ■   You can’t modify the contents of your app bundle
        • To include a writable data file with your app...
            ■ Build it as part of your app bundle
            ■ On first launch, copy it to your Documents directory




Tuesday, February 2, 2010                                            17
Archiving Objects




Tuesday, February 2, 2010   18
Archiving Objects
        • Next logical step from property lists
            ■ Include arbitrary classes
            ■ Complex object graphs


        • Used by Interface Builder for NIBs




Tuesday, February 2, 2010                         19
Making Objects Archivable
        • Conform to the <NSCoding> protocol




Tuesday, February 2, 2010                      20
Making Objects Archivable
        • Conform to the <NSCoding> protocol
            // Encode an object for an archive
            - (void)encodeWithCoder:(NSCoder *)coder
            {
              [super encodeWithCoder:coder];
              [coder encodeObject:name forKey:@“Name”];
              [coder encodeInteger:numberOfSides forKey:@“Sides”];
            }

            // Decode an object from an archive
            - (id)initWithCoder:(NSCoder *)coder
            {
              self = [super initWithCoder:coder];
              name = [[coder decodeObjectForKey:@“Name”] retain];
              numberOfSides = [coder decodeIntegerForKey:@“Side”];
            }



Tuesday, February 2, 2010                                            20
Archiving & Unarchiving Object Graphs




Tuesday, February 2, 2010                       21
Archiving & Unarchiving Object Graphs
        • Creating an archive
            NSArray *polygons = ...;
            NSString *path = ...;
            BOOL result = [NSKeyedArchiver archiveRootObject:polygons
                                                      toFile:path];




Tuesday, February 2, 2010                                               21
Archiving & Unarchiving Object Graphs
        • Creating an archive
            NSArray *polygons = ...;
            NSString *path = ...;
            BOOL result = [NSKeyedArchiver archiveRootObject:polygons
                                                      toFile:path];


        • Decoding an archive
            NSArray *polygons = nil;
            NSString *path = ...;
            polygons = [NSKeyedUnarchiver unarchiveObjectWithFile:path];




Tuesday, February 2, 2010                                                  21
More on Archiving Objects
        • “Archives and Serializations Programming Guide for Cocoa”
          http://developer.apple.com/documentation/Cocoa/
          Conceptual/Archiving/




Tuesday, February 2, 2010                                             22
The Joy of SQLite




Tuesday, February 2, 2010   23
SQLite
        • Complete SQL database in an ordinary file
        • Simple, compact, fast, reliable
        • No server
        • Free/Open Source Software
        • Great for embedded devices
            ■   Included on the iPhone platform




Tuesday, February 2, 2010                             24
When Not to Use SQLite
        • Multi-gigabyte databases
        • High concurrency (multiple writers)
        • Client-server applications
        • “Appropriate Uses for SQLite”
          http://www.sqlite.org/whentouse.html




Tuesday, February 2, 2010                        25
SQLite C API Basics




Tuesday, February 2, 2010     26
SQLite C API Basics
        • Open the database
            int sqlite3_open(const char *filename, sqlite3 **db);




Tuesday, February 2, 2010                                           26
SQLite C API Basics
        • Open the database
            int sqlite3_open(const char *filename, sqlite3 **db);

        • Execute a SQL statement
            int sqlite3_exec(sqlite3 *db, const char *sql,
                             int (*callback)(void*,int,char**,char**),
                             void *context, char **error);




Tuesday, February 2, 2010                                                26
SQLite C API Basics
        • Open the database
            int sqlite3_open(const char *filename, sqlite3 **db);

        • Execute a SQL statement
            int sqlite3_exec(sqlite3 *db, const char *sql,
                             int (*callback)(void*,int,char**,char**),
                             void *context, char **error);

            // Your callback
            int callback(void *context, int count,
                         char **values, char **columns);




Tuesday, February 2, 2010                                                26
SQLite C API Basics
        • Open the database
            int sqlite3_open(const char *filename, sqlite3 **db);

        • Execute a SQL statement
            int sqlite3_exec(sqlite3 *db, const char *sql,
                             int (*callback)(void*,int,char**,char**),
                             void *context, char **error);

            // Your callback
            int callback(void *context, int count,
                         char **values, char **columns);

        • Close the database
            int sqlite3_close(sqlite3 *db);




Tuesday, February 2, 2010                                                26
Demo:
        Simple SQLite




Tuesday, February 2, 2010   27
More on SQLite
        • “SQLite in 5 Minutes Or Less”
          http://www.sqlite.org/quickstart.html
        • “Intro to the SQLite C Interface”
          http://www.sqlite.org/cintro.html




Tuesday, February 2, 2010                         28
Core Data
        • Object-graph management and persistence framework
            ■   Makes it easy to save & load model objects
                 ■ Properties
                 ■ Relationships

            ■   Higher-level abstraction than SQLite or property lists
        • Available on the Mac OS X desktop
        • Now available on iPhone OS 3.0




Tuesday, February 2, 2010                                                29
Two classes you should know about...




Tuesday, February 2, 2010                      30
Two classes you should know about...
        • NSPredicate




Tuesday, February 2, 2010                      30
Two classes you should know about...
        • NSPredicate
            ■   “Used to define logical conditions used to constrain a search
                either for a fetch or for in-memory filtering.”




Tuesday, February 2, 2010                                                       30
Two classes you should know about...
        • NSPredicate
            ■ “Used to define logical conditions used to constrain a search
              either for a fetch or for in-memory filtering.”
            ■ -[NSPredicate predicateWithFormat:]




Tuesday, February 2, 2010                                                     30
Two classes you should know about...
        • NSPredicate
            ■ “Used to define logical conditions used to constrain a search
              either for a fetch or for in-memory filtering.”
            ■ -[NSPredicate predicateWithFormat:]

            ■ Simple comparisons:




Tuesday, February 2, 2010                                                     30
Two classes you should know about...
        • NSPredicate
            ■ “Used to define logical conditions used to constrain a search
              either for a fetch or for in-memory filtering.”
            ■ -[NSPredicate predicateWithFormat:]

            ■ Simple comparisons:

                 ■   grade == “7”




Tuesday, February 2, 2010                                                     30
Two classes you should know about...
        • NSPredicate
            ■ “Used to define logical conditions used to constrain a search
              either for a fetch or for in-memory filtering.”
            ■ -[NSPredicate predicateWithFormat:]

            ■ Simple comparisons:

                 ■   grade == “7”
                 ■   user.firstName like "Tom"




Tuesday, February 2, 2010                                                     30
Two classes you should know about...
        • NSPredicate
            ■ “Used to define logical conditions used to constrain a search
              either for a fetch or for in-memory filtering.”
            ■ -[NSPredicate predicateWithFormat:]

            ■ Simple comparisons:

                 ■   grade == “7”
                 ■   user.firstName like "Tom"
                 ■   “first contains [c]”chris”




Tuesday, February 2, 2010                                                     30
Two classes you should know about...
        • NSPredicate
            ■ “Used to define logical conditions used to constrain a search
              either for a fetch or for in-memory filtering.”
            ■ -[NSPredicate predicateWithFormat:]

            ■ Simple comparisons:

                 ■   grade == “7”
                 ■   user.firstName like "Tom"
                 ■   “first contains [c]”chris”
            ■   Many, many options:
                http://developer.apple.com/mac/library/documentation/cocoa/
                Conceptual/Predicates/Articles/pSyntax.html




Tuesday, February 2, 2010                                                     30
Two classes you should know about...




Tuesday, February 2, 2010                      31
Two classes you should know about...
        • NSEntityDescription




Tuesday, February 2, 2010                      31
Two classes you should know about...
        • NSEntityDescription
            ■   Used for inserting a new object into a Core Data Managed
                Object context




Tuesday, February 2, 2010                                                  31
Two classes you should know about...
        • NSEntityDescription
            ■ Used for inserting a new object into a Core Data Managed
              Object context
            ■ - [NSEntityDescription

              insertNewObjectForEntityForName:inManagedObjectContext:]




Tuesday, February 2, 2010                                                31
Two classes you should know about...
        • NSEntityDescription
            ■ Used for inserting a new object into a Core Data Managed
              Object context
            ■ - [NSEntityDescription

              insertNewObjectForEntityForName:inManagedObjectContext:]
            ■ See the documentation!




Tuesday, February 2, 2010                                                31
Two classes you should know about...
        • NSEntityDescription
            ■ Used for inserting a new object into a Core Data Managed
              Object context
            ■ - [NSEntityDescription

              insertNewObjectForEntityForName:inManagedObjectContext:]
            ■ See the documentation!

                 ■   http://developer.apple.com/mac/library/documentation/cocoa/
                     reference/CoreDataFramework/Classes/
                     NSEntityDescription_Class/NSEntityDescription.html




Tuesday, February 2, 2010                                                          31
Web Services




Tuesday, February 2, 2010   32
Your Application & The Cloud
        • Store & access remote data
        • May be under your control or someone else’s
        • Many Web 2.0 apps/sites provide developer API




Tuesday, February 2, 2010                                 33
“I made a location-based
         user-generated video blogging
         mashup... for pets!”




Tuesday, February 2, 2010                34
Integrating with Web Services
        • Non-goal of this class: teach you all about web services
            ■   Plenty of tutorials accessible, search on Google
        • Many are exposed via RESTful interfaces with XML or JSON
            ■   REpresentational State Transfer
                 ■ Stateless interactions
                 ■ Well defined client/server roles & interfaces

                 ■ e.g. HTTP


        • High level overview of parsing these types of data




Tuesday, February 2, 2010                                            35
XML




Tuesday, February 2, 2010   36
Options for Parsing XML
        • libxml2
            ■ Tree-based: easy to parse, entire tree in memory
            ■ Event-driven: less memory, more complex to manage state

            ■ Text reader: fast, easy to write, efficient


        • NSXMLParser
            ■   Event-driven API: simpler but less powerful than libxml2




Tuesday, February 2, 2010                                                  37
More on Parsing XML
        • Brent Simmons, “libxml2 + xmlTextReader on Macs”
          http://inessential.com/?comments=1&postid=3489
            ■   Includes example of parsing Twitter XML!
        • Big Nerd Ranch, “Parsing XML in Cocoa”
          http://weblog.bignerdranch.com/?p=48
            ■   Covers the basics of NSXMLReader




Tuesday, February 2, 2010                                    38
JSON




Tuesday, February 2, 2010   39
JavaScript Object Notation
        • More lightweight than XML
        • Looks a lot like a property list
            ■   Arrays, dictionaries, strings, numbers
        • Open source json-framework wrapper for Objective-C




Tuesday, February 2, 2010                                      40
What does a JSON object look like?




Tuesday, February 2, 2010                    41
What does a JSON object look like?

                      {




Tuesday, February 2, 2010                    41
What does a JSON object look like?

                      {
                            “instructor” : “Josh Shaffer”,




Tuesday, February 2, 2010                                    41
What does a JSON object look like?

                      {
                            “instructor” : “Josh Shaffer”,
                            “students” : 60,




Tuesday, February 2, 2010                                    41
What does a JSON object look like?

                      {
                            “instructor” : “Josh Shaffer”,
                            “students” : 60,
                            “itunes-u” : true,




Tuesday, February 2, 2010                                    41
What does a JSON object look like?

                      {
                            “instructor” : “Josh Shaffer”,
                            “students” : 60,
                            “itunes-u” : true,
                            “midterm-exam” : null,




Tuesday, February 2, 2010                                    41
What does a JSON object look like?

                      {
                            “instructor” : “Josh Shaffer”,
                            “students” : 60,
                            “itunes-u” : true,
                            “midterm-exam” : null,
                            “assignments” : [ “WhatATool”,




Tuesday, February 2, 2010                                    41
What does a JSON object look like?

                      {
                            “instructor” : “Josh Shaffer”,
                            “students” : 60,
                            “itunes-u” : true,
                            “midterm-exam” : null,
                            “assignments” : [ “WhatATool”,
                                               “HelloPoly”,




Tuesday, February 2, 2010                                     41
What does a JSON object look like?

                      {
                            “instructor” : “Josh Shaffer”,
                            “students” : 60,
                            “itunes-u” : true,
                            “midterm-exam” : null,
                            “assignments” : [ “WhatATool”,
                                               “HelloPoly”,
                                               “Presence” ]




Tuesday, February 2, 2010                                     41
What does a JSON object look like?

                      {
                            “instructor” : “Josh Shaffer”,
                            “students” : 60,
                            “itunes-u” : true,
                            “midterm-exam” : null,
                            “assignments” : [ “WhatATool”,
                                               “HelloPoly”,
                                               “Presence” ]
                      }




Tuesday, February 2, 2010                                     41
Using json-framework
        • Reading a JSON string into Foundation objects




Tuesday, February 2, 2010                                 42
Using json-framework
        • Reading a JSON string into Foundation objects
            #import <JSON/JSON.h>




Tuesday, February 2, 2010                                 42
Using json-framework
        • Reading a JSON string into Foundation objects
            #import <JSON/JSON.h>

            // Get a JSON string from the cloud
            NSString *jsonString = ...;




Tuesday, February 2, 2010                                 42
Using json-framework
        • Reading a JSON string into Foundation objects
            #import <JSON/JSON.h>

            // Get a JSON string from the cloud
            NSString *jsonString = ...;

            // Parsing will result in Foundation objects
            // Top level may be an NSDictionary or an NSArray
            id object = [jsonString JSONValue];




Tuesday, February 2, 2010                                       42
Using json-framework
        • Writing a JSON string from Foundation objects




Tuesday, February 2, 2010                                 43
Using json-framework
        • Writing a JSON string from Foundation objects
            // Create some data in your app




Tuesday, February 2, 2010                                 43
Using json-framework
        • Writing a JSON string from Foundation objects
            // Create some data in your app
            NSDictionary *dictionary = ...;

            // Convert into a JSON string before sending to the cloud




Tuesday, February 2, 2010                                               43
Using json-framework
        • Writing a JSON string from Foundation objects
            // Create some data in your app
            NSDictionary *dictionary = ...;

            // Convert into a JSON string before sending to the cloud
            jsonString = [dictionary JSONRepresentation];




Tuesday, February 2, 2010                                               43
Demo:
        Flickr API with JSON




Tuesday, February 2, 2010      44
More on JSON
        • “JSON Parser/Generator for Objective-C”
          http://code.google.com/p/json-framework/
        • “Introducing JSON”
          http://www.json.org/




Tuesday, February 2, 2010                            45
Apple Push Notification Service




Tuesday, February 2, 2010                 46
Overview




Tuesday, February 2, 2010   47
Overview

       • Show badges, alerts and play sounds without app running




Tuesday, February 2, 2010                                          47
Overview

       • Show badges, alerts and play sounds without app running
       • Minimal server infrastructure needed




Tuesday, February 2, 2010                                          47
Overview

       • Show badges, alerts and play sounds without app running
       • Minimal server infrastructure needed
       • Preserves battery life: 1 versus n TCP/IP connections


                                  Apple
                     Server       Push
                                 Service




Tuesday, February 2, 2010                                          47
Using the Service




                            Server




Tuesday, February 2, 2010            48
Using the Service
       What you need




                            Server




Tuesday, February 2, 2010            48
Using the Service
       What you need




                            Server




Tuesday, February 2, 2010            48
Using the Service
       What you need




                            Server


                                     edu.stanford.cs193.app




Tuesday, February 2, 2010                                     48
Using the Service
       What you need




                            Server


                                     edu.stanford.cs193.app




Tuesday, February 2, 2010                                     48
Using the Service
       What you do




                                      Apple
                                      Push
                            Server   Service




Tuesday, February 2, 2010                      49
Using the Service
       1. Register with the service




                             Apple
                             Push     Chris’s iPhone
                            Service




Tuesday, February 2, 2010                              50
Using the Service




                                     Chris’s iPhone
                            Server




Tuesday, February 2, 2010                             51
Using the Service
       2. Send token to your server




                            Server

                      Chris’s iPhone




Tuesday, February 2, 2010              51
Using the Service
       3. Send notifications




                                        Apple
                                        Push
                            Server     Service


                      Chris’s iPhone




Tuesday, February 2, 2010                        52
Using the Service
       3. Send notifications




                                        Apple
                                        Push
                                        JSON
                                       Service
                            Server

                      Chris’s iPhone




Tuesday, February 2, 2010                        52
Using the Service
       4. Receive notifications




                             Apple
                             Push
                            Service




Tuesday, February 2, 2010             53
Using the Service
       4. Receive notifications




                             Apple
                             Push     JSON
                            Service




Tuesday, February 2, 2010                    53
Using the Service
       1. Register with the service




                             Apple
                             Push     Chris’s iPhone
                            Service




Tuesday, February 2, 2010                              54
Using the Service
       1. Register with the service




                             Apple
                             Push     Chris’s iPhone
                            Service




Tuesday, February 2, 2010                              54
Registering with the Service
       Application launch
       • UIKit API in UIApplication.h to register
               ■   Pass the types you want to receive


             -(void)application:(UIApplication *)application
                      didFinishLaunchingWithOptions:(NSDictionary *)options
         {
                   // Register this app on this device
                   UIRemoteNotificationType myTypes = UIRemoteNotificationTypeSounds |
                                                       UIRemoteNotificationTypeBadges;
                   [application registerForRemoteNotificationTypes:myTypes];
         }




Tuesday, February 2, 2010                                                                55
Registering with the Service
       Delegate callbacks




Tuesday, February 2, 2010             56
Registering with the Service
       Delegate callbacks

             - (void)application:(UIApplication *)application
                didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)token
         {
                // Phone home with device token
         }




Tuesday, February 2, 2010                                                          56
Registering with the Service
       Delegate callbacks

             - (void)application:(UIApplication *)application
                didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)token
         {
                // Phone home with device token
         }




             - (void)application:(UIApplication *)application
                didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
         {
                // Oh noes! Check your Provisioning Profile on device and in Xcode
         }




Tuesday, February 2, 2010                                                            56
Registering with the Service




                    96385da767191121a851963983fdac9bbdf74dcf6219ae14ed8d08228




Tuesday, February 2, 2010                                                       57
Registering with the Service
       The device token




                    96385da767191121a851963983fdac9bbdf74dcf6219ae14ed8d08228




Tuesday, February 2, 2010                                                       57
Registering with the Service
       The device token
       • Uniquely identifies device




                    96385da767191121a851963983fdac9bbdf74dcf6219ae14ed8d08228




Tuesday, February 2, 2010                                                       57
Registering with the Service
       The device token
       • Uniquely identifies device
              ■   Distinct from -[UIDevice deviceIdentifier]




                    96385da767191121a851963983fdac9bbdf74dcf6219ae14ed8d08228




Tuesday, February 2, 2010                                                       57
Registering with the Service
       The device token
       • Uniquely identifies device
              ■   Distinct from -[UIDevice deviceIdentifier]
       • Just call registration API again if token is needed



                    96385da767191121a851963983fdac9bbdf74dcf6219ae14ed8d08228




Tuesday, February 2, 2010                                                       57
Registering for Notifications
       Optional callbacks and methods

       • UIApplicationDelegate
          - (void)application:(UIApplication *)application
               didReceiveRemoteNotification:(NSDictionary *)userInfo




Tuesday, February 2, 2010                                              58
Registering for Notifications
       Optional callbacks and methods

       • UIApplicationDelegate
          - (void)application:(UIApplication *)application
               didReceiveRemoteNotification:(NSDictionary *)userInfo




       • UIApplication
          - (UIRemoteNotificationType)enabledRemoteNotificationTypes




Tuesday, February 2, 2010                                              58
Using the Service




                                 Chris’s iPhone
                        Server




Tuesday, February 2, 2010                         59
Using the Service
       2. Send token to your server




                        Server

                     Chris’s iPhone




Tuesday, February 2, 2010             59
Using the Service
       3. Send notifications




                                       Apple
                                       Push
                        Server        Service


                     Chris’s iPhone




Tuesday, February 2, 2010                       60
Using the Service
       3. Send notifications




                                       Apple
                                       Push
                                        JSON
                        Server        Service


                     Chris’s iPhone



                       edu.s.cs193




Tuesday, February 2, 2010                       60
Sending Notifications



         {
              "aps" : {
                  "alert" : "Jen: Sushi at 10?",
                  "badge" : 1,
                  "sound" : "Jingle.aiff"
              },
              "acme1" : "conversation9964"
         }




Tuesday, February 2, 2010                          61
Sending Notifications
       Message payload




         {
              "aps" : {
                  "alert" : "Jen: Sushi at 10?",
                  "badge" : 1,
                  "sound" : "Jingle.aiff"
              },
              "acme1" : "conversation9964"
         }




Tuesday, February 2, 2010                          61
Sending Notifications
       Message payload
       • Strict RFC 4627 JSON


         {
              "aps" : {
                  "alert" : "Jen: Sushi at 10?",
                  "badge" : 1,
                  "sound" : "Jingle.aiff"
              },
              "acme1" : "conversation9964"
         }




Tuesday, February 2, 2010                          61
Sending Notifications
       Message payload
       • Strict RFC 4627 JSON
       • 256 byte maximum

         {
              "aps" : {
                  "alert" : "Jen: Sushi at 10?",
                  "badge" : 1,
                  "sound" : "Jingle.aiff"
              },
              "acme1" : "conversation9964"
         }




Tuesday, February 2, 2010                          61
Sending Notifications
       Message payload
       • aps dictionary reserved for the sound, badge or alert keys
              ■   All keys optional
         {
               "aps" : {
                   "alert" : "Jen: Sushi at 10?",
                   "badge" : 1,
                   "sound" : "Jingle.aiff"
               },
               "acme1" : "conversation9964"
         }




       • Rest of payload is for your app


Tuesday, February 2, 2010                                             62
Sending Notifications
       Message payload
       • aps dictionary reserved for the sound, badge or alert keys
              ■   All keys optional
         {
               "aps" : {
                   "alert" : "Jen: Sushi at 10?",
                   "badge" : 1,
                   "sound" : "Jingle.aiff"
               },
               "acme1" : "conversation9964"
         }




       • Rest of payload is for your app


Tuesday, February 2, 2010                                             62
Badges
       badge key, integer value
       • Positive integer
              ■   Or omit to remove

        {
              "aps" : {
                  "badge" : 1
              }
        }




Tuesday, February 2, 2010             63
Badges
       badge key, integer value
       • Positive integer
              ■   Or omit to remove

        {
              "aps" : {
                  "badge" : 1
              }
        }




Tuesday, February 2, 2010             63
Sounds
       sound key, string value
       • Either a filename in app bundle   {
              ■   linear PCM                   "aps" : {
                                                   "sound" : "Jingle.aiff"
              ■   MA4                          }
                                           }
              ■   µLaw
              ■   aLaw
       • Or “default”
       • Vibration is automatic




Tuesday, February 2, 2010                                                    64
Alerts
       alert key, string or dictionary value
       • Simplest form is just a string value

         {
                  "aps" : {
                      "alert" : "Jen: Sushi at 10?"
                  }
         }




       • Can be localized (see documentation)
       • Can also customize the text on the view button
              ■    or omit it


Tuesday, February 2, 2010                                 65
Alerts
       alert key, string or dictionary value
       • Simplest form is just a string value

         {
                  "aps" : {
                      "alert" : "Jen: Sushi at 10?"
                  }
         }




       • Can be localized (see documentation)
       • Can also customize the text on the view button
              ■    or omit it


Tuesday, February 2, 2010                                 65
Sending the Payload
       Send JSON that is stripped of whitespace

         {
               "aps" : {
                   "alert" : "Jen: Sushi at 10?",
                   "badge" : 1,                     150 bytes
                   "sound" : "Jingle1.aiff"
               },
               "acme1" : "conversation9964"




Tuesday, February 2, 2010                                       66
Sending the Payload
       Send JSON that is stripped of whitespace

         {"aps":{"alert":"Jen: Sushi at 10?","badge":
         1,
         "sound":"Jingle.aiff"},"acme1":"conversation
         9964"}                                         96 bytes




Tuesday, February 2, 2010                                          66
Demo:
        Pushing to the Flickr app




Tuesday, February 2, 2010           67
NSUserDefaults recap
        (time permitting)




Tuesday, February 2, 2010      68
NSUserDefaults
        • Convenient way to store settings and lightweight state
            ■ Arrays, dictionaries, strings, numbers, dates, raw data
            ■ Settings bundles can be created so that user defaults can be set

              from Settings app
            ■ Internally stored as property lists




Tuesday, February 2, 2010                                                        69
Reading & Writing User Defaults
        • Key-value store
        • Base methods accept and return objects for values
         + (NSUserDefaults *)standardUserDefaults;

         - (id)objectForKey:(NSString *)defaultName;
         - (void)setObject:(id)value forKey:(NSString *)defaultName;
         - (void)removeObjectForKey:(NSString *)defaultName;

         - (BOOL)synchronize;




Tuesday, February 2, 2010                                              70
Reading & Writing User Defaults
        • Many convenience methods that ‘box’ and ‘unbox’ the object
             ■   and perform type checking
         -   (NSString *)stringForKey:(NSString *)defaultName;
         -   (NSArray *)arrayForKey:(NSString *)defaultName;
         -   (NSDictionary *)dictionaryForKey:(NSString *)defaultName;
         -   (NSData *)dataForKey:(NSString *)defaultName;
         -   (NSArray *)stringArrayForKey:(NSString *)defaultName;
         -   (NSInteger)integerForKey:(NSString *)defaultName;
         -   (float)floatForKey:(NSString *)defaultName;
         -   (double)doubleForKey:(NSString *)defaultName;
         -   (BOOL)boolForKey:(NSString *)defaultName;

         - (void)setInteger:(NSInteger)value forKey:(NSString *)
         defaultName;
         - (void)setFloat:(float)value forKey:(NSString *)defaultName;
         - (void)setDouble:(double)value forKey:(NSString *)defaultName;
         - (void)setBool:(BOOL)value forKey:(NSString *)defaultName;


Tuesday, February 2, 2010                                                  71
-[NSUserDefaults synchronize]
        • Call [[NSUserDefaults standardUserDefaults] synchronize] to
          write changes to disk
        • Also loads external changes from disk (useful on Mac OS X)




Tuesday, February 2, 2010                                               72
More on NSUserDefaults
        • “User Defaults Programming Topics for Cocoa”
          http://developer.apple.com/mac/library/documentation/
          Cocoa/Conceptual/UserDefaults/Tasks/UsingDefaults.html




Tuesday, February 2, 2010                                          73
Demo:
        NSUserDefaults and Settings




Tuesday, February 2, 2010             74
Recap
        • Property lists, NSUserDefaults
            ■   Quick & easy, but limited
        • Archived objects
            ■   More flexible, but require writing a lot of code
        • SQLite
            ■   Elegant solution for many types of problems
        • XML and JSON
            ■ Low-overhead options for talking to “the cloud”
            ■ Apple Push Notification Service pushes JSON from your server to

              devices




Tuesday, February 2, 2010                                                       75
Questions?




Tuesday, February 2, 2010   76

More Related Content

What's hot

Non-Technical Introduction to CrossRef for Libraries
Non-Technical Introduction to CrossRef for LibrariesNon-Technical Introduction to CrossRef for Libraries
Non-Technical Introduction to CrossRef for LibrariesCrossref
 
NoSQL - Post-Relational Databases - BarCamp Ruhr3
NoSQL - Post-Relational Databases - BarCamp Ruhr3NoSQL - Post-Relational Databases - BarCamp Ruhr3
NoSQL - Post-Relational Databases - BarCamp Ruhr3Jonathan Weiss
 
No SQL - BarCamp Nürnberg 2010
No SQL - BarCamp Nürnberg 2010No SQL - BarCamp Nürnberg 2010
No SQL - BarCamp Nürnberg 2010Jonathan Weiss
 
Getting Started with Dojo Toolkit
Getting Started with Dojo ToolkitGetting Started with Dojo Toolkit
Getting Started with Dojo ToolkitThomas Koch
 
Getting Started with MongoDB (TCF ITPC 2014)
Getting Started with MongoDB (TCF ITPC 2014)Getting Started with MongoDB (TCF ITPC 2014)
Getting Started with MongoDB (TCF ITPC 2014)Michael Redlich
 
The Semantic Web for Librarians and Publishers, by Michael Keller, Stanford U...
The Semantic Web for Librarians and Publishers, by Michael Keller, Stanford U...The Semantic Web for Librarians and Publishers, by Michael Keller, Stanford U...
The Semantic Web for Librarians and Publishers, by Michael Keller, Stanford U...Charleston Conference
 
Frontend Engineer Toolbox
Frontend Engineer ToolboxFrontend Engineer Toolbox
Frontend Engineer ToolboxYnon Perek
 
Sqlpo Presentation
Sqlpo PresentationSqlpo Presentation
Sqlpo Presentationsandook
 
Pinterest的数据库分片架构
Pinterest的数据库分片架构Pinterest的数据库分片架构
Pinterest的数据库分片架构Tommy Chiu
 

What's hot (9)

Non-Technical Introduction to CrossRef for Libraries
Non-Technical Introduction to CrossRef for LibrariesNon-Technical Introduction to CrossRef for Libraries
Non-Technical Introduction to CrossRef for Libraries
 
NoSQL - Post-Relational Databases - BarCamp Ruhr3
NoSQL - Post-Relational Databases - BarCamp Ruhr3NoSQL - Post-Relational Databases - BarCamp Ruhr3
NoSQL - Post-Relational Databases - BarCamp Ruhr3
 
No SQL - BarCamp Nürnberg 2010
No SQL - BarCamp Nürnberg 2010No SQL - BarCamp Nürnberg 2010
No SQL - BarCamp Nürnberg 2010
 
Getting Started with Dojo Toolkit
Getting Started with Dojo ToolkitGetting Started with Dojo Toolkit
Getting Started with Dojo Toolkit
 
Getting Started with MongoDB (TCF ITPC 2014)
Getting Started with MongoDB (TCF ITPC 2014)Getting Started with MongoDB (TCF ITPC 2014)
Getting Started with MongoDB (TCF ITPC 2014)
 
The Semantic Web for Librarians and Publishers, by Michael Keller, Stanford U...
The Semantic Web for Librarians and Publishers, by Michael Keller, Stanford U...The Semantic Web for Librarians and Publishers, by Michael Keller, Stanford U...
The Semantic Web for Librarians and Publishers, by Michael Keller, Stanford U...
 
Frontend Engineer Toolbox
Frontend Engineer ToolboxFrontend Engineer Toolbox
Frontend Engineer Toolbox
 
Sqlpo Presentation
Sqlpo PresentationSqlpo Presentation
Sqlpo Presentation
 
Pinterest的数据库分片架构
Pinterest的数据库分片架构Pinterest的数据库分片架构
Pinterest的数据库分片架构
 

Viewers also liked

06 View Controllers
06 View Controllers06 View Controllers
06 View ControllersMahmoud
 
04 Model View Controller
04 Model View Controller04 Model View Controller
04 Model View ControllerMahmoud
 
02 Objective C
02 Objective C02 Objective C
02 Objective CMahmoud
 
01 Introduction
01 Introduction01 Introduction
01 IntroductionMahmoud
 
CS193P Lecture 5 View Animation
CS193P Lecture 5 View AnimationCS193P Lecture 5 View Animation
CS193P Lecture 5 View Animationonoaonoa
 

Viewers also liked (8)

06 View Controllers
06 View Controllers06 View Controllers
06 View Controllers
 
iOS: View Controllers
iOS: View ControllersiOS: View Controllers
iOS: View Controllers
 
04 Model View Controller
04 Model View Controller04 Model View Controller
04 Model View Controller
 
02 Objective C
02 Objective C02 Objective C
02 Objective C
 
01 Introduction
01 Introduction01 Introduction
01 Introduction
 
05 Views
05 Views05 Views
05 Views
 
CS193P Lecture 5 View Animation
CS193P Lecture 5 View AnimationCS193P Lecture 5 View Animation
CS193P Lecture 5 View Animation
 
Animation in iOS
Animation in iOSAnimation in iOS
Animation in iOS
 

Similar to 09 Data

SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniquesjoaopmaia
 
Ruby on CouchDB - SimplyStored and RockingChair
Ruby on CouchDB - SimplyStored and RockingChairRuby on CouchDB - SimplyStored and RockingChair
Ruby on CouchDB - SimplyStored and RockingChairJonathan Weiss
 
Fluentd meetup intro
Fluentd meetup introFluentd meetup intro
Fluentd meetup introtd_kiyoto
 
Best Practices - Mobile Developer Summit
Best Practices - Mobile Developer SummitBest Practices - Mobile Developer Summit
Best Practices - Mobile Developer Summitwolframkriesing
 
iOS: Using persistant storage
iOS: Using persistant storageiOS: Using persistant storage
iOS: Using persistant storageJussi Pohjolainen
 
Creating a Single View Part 2: Loading Disparate Source Data and Creating a S...
Creating a Single View Part 2: Loading Disparate Source Data and Creating a S...Creating a Single View Part 2: Loading Disparate Source Data and Creating a S...
Creating a Single View Part 2: Loading Disparate Source Data and Creating a S...MongoDB
 
Polylog: A Log-Based Architecture for Distributed Systems
Polylog: A Log-Based Architecture for Distributed SystemsPolylog: A Log-Based Architecture for Distributed Systems
Polylog: A Log-Based Architecture for Distributed SystemsKamil Sindi
 

Similar to 09 Data (20)

SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniques
 
занятие8
занятие8занятие8
занятие8
 
Meet Couch DB
Meet Couch DBMeet Couch DB
Meet Couch DB
 
Ruby on CouchDB - SimplyStored and RockingChair
Ruby on CouchDB - SimplyStored and RockingChairRuby on CouchDB - SimplyStored and RockingChair
Ruby on CouchDB - SimplyStored and RockingChair
 
Fluentd meetup intro
Fluentd meetup introFluentd meetup intro
Fluentd meetup intro
 
04 Reports
04 Reports04 Reports
04 Reports
 
Riak Intro
Riak IntroRiak Intro
Riak Intro
 
Mongo db
Mongo dbMongo db
Mongo db
 
04 reports
04 reports04 reports
04 reports
 
06 data
06 data06 data
06 data
 
Lecture 04
Lecture 04Lecture 04
Lecture 04
 
Everyday - mongodb
Everyday - mongodbEveryday - mongodb
Everyday - mongodb
 
Best Practices - Mobile Developer Summit
Best Practices - Mobile Developer SummitBest Practices - Mobile Developer Summit
Best Practices - Mobile Developer Summit
 
Using SQLite
Using SQLiteUsing SQLite
Using SQLite
 
noSQL @ QCon SP
noSQL @ QCon SPnoSQL @ QCon SP
noSQL @ QCon SP
 
Node.js - A Quick Tour II
Node.js - A Quick Tour IINode.js - A Quick Tour II
Node.js - A Quick Tour II
 
iOS: Using persistant storage
iOS: Using persistant storageiOS: Using persistant storage
iOS: Using persistant storage
 
Creating a Single View Part 2: Loading Disparate Source Data and Creating a S...
Creating a Single View Part 2: Loading Disparate Source Data and Creating a S...Creating a Single View Part 2: Loading Disparate Source Data and Creating a S...
Creating a Single View Part 2: Loading Disparate Source Data and Creating a S...
 
Persistence Smoothie
Persistence SmoothiePersistence Smoothie
Persistence Smoothie
 
Polylog: A Log-Based Architecture for Distributed Systems
Polylog: A Log-Based Architecture for Distributed SystemsPolylog: A Log-Based Architecture for Distributed Systems
Polylog: A Log-Based Architecture for Distributed Systems
 

More from Mahmoud

مهارات التفكير الإبتكاري كيف تكون مبدعا؟
مهارات التفكير الإبتكاري  كيف تكون مبدعا؟مهارات التفكير الإبتكاري  كيف تكون مبدعا؟
مهارات التفكير الإبتكاري كيف تكون مبدعا؟Mahmoud
 
كيف تقوى ذاكرتك
كيف تقوى ذاكرتككيف تقوى ذاكرتك
كيف تقوى ذاكرتكMahmoud
 
مهارات التعامل مع الغير
مهارات التعامل مع الغيرمهارات التعامل مع الغير
مهارات التعامل مع الغيرMahmoud
 
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكمستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكمMahmoud
 
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائقتطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائقMahmoud
 
الشخصية العبقرية
الشخصية العبقريةالشخصية العبقرية
الشخصية العبقريةMahmoud
 
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيه
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيهمهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيه
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيهMahmoud
 
مهارات التفكير الإبتكاري كيف تكون مبدعا؟
مهارات التفكير الإبتكاري  كيف تكون مبدعا؟مهارات التفكير الإبتكاري  كيف تكون مبدعا؟
مهارات التفكير الإبتكاري كيف تكون مبدعا؟Mahmoud
 
مهارات التعامل مع الغير
مهارات التعامل مع الغيرمهارات التعامل مع الغير
مهارات التعامل مع الغيرMahmoud
 
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائقتطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائقMahmoud
 
كيف تقوى ذاكرتك
كيف تقوى ذاكرتككيف تقوى ذاكرتك
كيف تقوى ذاكرتكMahmoud
 
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكمستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكمMahmoud
 
الشخصية العبقرية
الشخصية العبقريةالشخصية العبقرية
الشخصية العبقريةMahmoud
 
Accident Investigation
Accident InvestigationAccident Investigation
Accident InvestigationMahmoud
 
Investigation Skills
Investigation SkillsInvestigation Skills
Investigation SkillsMahmoud
 
Building Papers
Building PapersBuilding Papers
Building PapersMahmoud
 
Appleipad 100205071918 Phpapp02
Appleipad 100205071918 Phpapp02Appleipad 100205071918 Phpapp02
Appleipad 100205071918 Phpapp02Mahmoud
 
Operatingsystemwars 100209023952 Phpapp01
Operatingsystemwars 100209023952 Phpapp01Operatingsystemwars 100209023952 Phpapp01
Operatingsystemwars 100209023952 Phpapp01Mahmoud
 
A Basic Modern Russian Grammar
A Basic Modern Russian Grammar A Basic Modern Russian Grammar
A Basic Modern Russian Grammar Mahmoud
 

More from Mahmoud (20)

مهارات التفكير الإبتكاري كيف تكون مبدعا؟
مهارات التفكير الإبتكاري  كيف تكون مبدعا؟مهارات التفكير الإبتكاري  كيف تكون مبدعا؟
مهارات التفكير الإبتكاري كيف تكون مبدعا؟
 
كيف تقوى ذاكرتك
كيف تقوى ذاكرتككيف تقوى ذاكرتك
كيف تقوى ذاكرتك
 
مهارات التعامل مع الغير
مهارات التعامل مع الغيرمهارات التعامل مع الغير
مهارات التعامل مع الغير
 
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكمستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
 
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائقتطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
 
الشخصية العبقرية
الشخصية العبقريةالشخصية العبقرية
الشخصية العبقرية
 
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيه
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيهمهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيه
مهارات كتابه السيرة الذاتيه واجتياز المقابله الشخصيه
 
مهارات التفكير الإبتكاري كيف تكون مبدعا؟
مهارات التفكير الإبتكاري  كيف تكون مبدعا؟مهارات التفكير الإبتكاري  كيف تكون مبدعا؟
مهارات التفكير الإبتكاري كيف تكون مبدعا؟
 
مهارات التعامل مع الغير
مهارات التعامل مع الغيرمهارات التعامل مع الغير
مهارات التعامل مع الغير
 
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائقتطوير الذاكرة    تعلم كيف تحفظ 56 كلمة كل 10 دقائق
تطوير الذاكرة تعلم كيف تحفظ 56 كلمة كل 10 دقائق
 
كيف تقوى ذاكرتك
كيف تقوى ذاكرتككيف تقوى ذاكرتك
كيف تقوى ذاكرتك
 
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكمستيفن كوفي ( ادارة الاولويات ) لايفوتكم
ستيفن كوفي ( ادارة الاولويات ) لايفوتكم
 
الشخصية العبقرية
الشخصية العبقريةالشخصية العبقرية
الشخصية العبقرية
 
Accident Investigation
Accident InvestigationAccident Investigation
Accident Investigation
 
Investigation Skills
Investigation SkillsInvestigation Skills
Investigation Skills
 
Building Papers
Building PapersBuilding Papers
Building Papers
 
Appleipad 100205071918 Phpapp02
Appleipad 100205071918 Phpapp02Appleipad 100205071918 Phpapp02
Appleipad 100205071918 Phpapp02
 
Operatingsystemwars 100209023952 Phpapp01
Operatingsystemwars 100209023952 Phpapp01Operatingsystemwars 100209023952 Phpapp01
Operatingsystemwars 100209023952 Phpapp01
 
A Basic Modern Russian Grammar
A Basic Modern Russian Grammar A Basic Modern Russian Grammar
A Basic Modern Russian Grammar
 
Teams Ar
Teams ArTeams Ar
Teams Ar
 

Recently uploaded

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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
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
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
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
 
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
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
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
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 

Recently uploaded (20)

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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
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
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
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
 
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
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
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
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 

09 Data

  • 1. CS193P - Lecture 9 iPhone Application Development Data in Your iPhone App Chris Marcellino Tuesday, February 2, 2010 1
  • 2. Today’s Topics • Data in Your iPhone App ■ Saving & loading local data ■ Accessing remote data over the Internet Tuesday, February 2, 2010 2
  • 3. Today’s Topics • Property Lists, NSUserDefaults and Settings • iPhone’s File System • Archiving Objects • The Joy of SQLite • JSON • Apple Push Notification Service Tuesday, February 2, 2010 3
  • 5. Property Lists • Convenient way to store a small amount of data ■ Arrays, dictionaries, strings, numbers, dates, raw data ■ Human-readable XML or binary format • NSUserDefaults class uses property lists under the hood Tuesday, February 2, 2010 5
  • 6. When Not to Use Property Lists • More than a few hundred KB of data ■ Loading a property list is all-or-nothing • Complex object graphs • Custom object types • Multiple writers (e.g. not ACID) Tuesday, February 2, 2010 6
  • 7. Reading & Writing Property Lists • NSArray and NSDictionary convenience methods • Operate recursively // Writing - (BOOL)writeToFile:(NSString *)aPath atomically:(BOOL)flag; - (BOOL)writeToURL:(NSURL *)aURL atomically:(BOOL)flag; // Reading - (id)initWithContentsOfFile:(NSString *)aPath; - (id)initWithContentsOfURL:(NSURL *)aURL; Tuesday, February 2, 2010 7
  • 8. Writing an Array to Disk Tuesday, February 2, 2010 8
  • 9. Writing an Array to Disk NSArray *array = [NSArray arrayWithObjects:@“Foo”, Tuesday, February 2, 2010 8
  • 10. Writing an Array to Disk NSArray *array = [NSArray arrayWithObjects:@“Foo”, [NSNumber numberWithBool:YES], Tuesday, February 2, 2010 8
  • 11. Writing an Array to Disk NSArray *array = [NSArray arrayWithObjects:@“Foo”, [NSNumber numberWithBool:YES], [NSDate dateWithTimeIntervalSinceNow:60], Tuesday, February 2, 2010 8
  • 12. Writing an Array to Disk NSArray *array = [NSArray arrayWithObjects:@“Foo”, [NSNumber numberWithBool:YES], [NSDate dateWithTimeIntervalSinceNow:60], nil]; Tuesday, February 2, 2010 8
  • 13. Writing an Array to Disk NSArray *array = [NSArray arrayWithObjects:@“Foo”, [NSNumber numberWithBool:YES], [NSDate dateWithTimeIntervalSinceNow:60], nil]; [array writeToFile:@“MyArray.plist” atomically:YES]; Tuesday, February 2, 2010 8
  • 14. Writing an Array to Disk NSArray *array = [NSArray arrayWithObjects:@“Foo”, [NSNumber numberWithBool:YES], [NSDate dateWithTimeIntervalSinceNow:60], nil]; [array writeToFile:@“MyArray.plist” atomically:YES]; <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <array> <string>Foo</string> <true/> <date>2010-02-02T09:26:18Z</date> </array> </plist> Tuesday, February 2, 2010 8
  • 15. Writing a Dictionary to Disk Tuesday, February 2, 2010 9
  • 16. Writing a Dictionary to Disk NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: Tuesday, February 2, 2010 9
  • 17. Writing a Dictionary to Disk NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: @“Bob”, @“Name”, Tuesday, February 2, 2010 9
  • 18. Writing a Dictionary to Disk NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: @“Bob”, @“Name”, [NSNumber numberWithInt:9], @“Lecture”, Tuesday, February 2, 2010 9
  • 19. Writing a Dictionary to Disk NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: @“Bob”, @“Name”, [NSNumber numberWithInt:9], @“Lecture”, nil]; Tuesday, February 2, 2010 9
  • 20. Writing a Dictionary to Disk NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: @“Bob”, @“Name”, [NSNumber numberWithInt:9], @“Lecture”, nil]; [dict writeToFile:@“MyDict.plist” atomically:YES]; Tuesday, February 2, 2010 9
  • 21. Writing a Dictionary to Disk NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: @“Bob”, @“Name”, [NSNumber numberWithInt:9], @“Lecture”, nil]; [dict writeToFile:@“MyDict.plist” atomically:YES]; <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Name</key> <string>Bob</string> <key>Lecture</key> <integer>10</integer> </dict> </plist> Tuesday, February 2, 2010 9
  • 22. NSPropertyListSerialization • Allows finer-grained control ■ File format ■ More descriptive errors ■ Mutability Tuesday, February 2, 2010 10
  • 23. NSPropertyListSerialization • Allows finer-grained control ■ File format ■ More descriptive errors ■ Mutability // Property list to NSData + (NSData *)dataFromPropertyList:(id)plist format:(NSPropertyListFormat)format errorDescription:(NSString **)errorString; // NSData to property list + (id)propertyListFromData:(NSData *)data mutabilityOption:(NSPropertyListMutabilityOptions)opt format:(NSPropertyListFormat *)format errorDescription:(NSString **)errorString; Tuesday, February 2, 2010 10
  • 24. More on Property Lists • “Property List Programming Guide for Cocoa” http://developer.apple.com/documentation/Cocoa/ Conceptual/PropertyLists/ Tuesday, February 2, 2010 11
  • 25. iPhone’s File System Tuesday, February 2, 2010 12
  • 26. Keeping Applications Separate Image (cc) by davidsilver on Flickr Tuesday, February 2, 2010 13
  • 27. Why Keep Applications Separate? • Security • Privacy • Cleanup after deleting an app Tuesday, February 2, 2010 14
  • 28. Home Directory Layout Tuesday, February 2, 2010 15
  • 29. Home Directory Layout • Each app has its own set of directories Tuesday, February 2, 2010 15
  • 30. Home Directory Layout • Each app has its own set of directories • <Application Home> Tuesday, February 2, 2010 15
  • 31. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app Tuesday, February 2, 2010 15
  • 32. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app ■ MyApp Tuesday, February 2, 2010 15
  • 33. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app ■ MyApp ■ MainWindow.nib Tuesday, February 2, 2010 15
  • 34. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app ■ MyApp ■ MainWindow.nib ■ SomeImage.png Tuesday, February 2, 2010 15
  • 35. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app ■ MyApp ■ MainWindow.nib ■ SomeImage.png ■ Documents Tuesday, February 2, 2010 15
  • 36. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app ■ MyApp ■ MainWindow.nib ■ SomeImage.png ■ Documents ■ Library Tuesday, February 2, 2010 15
  • 37. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app ■ MyApp ■ MainWindow.nib ■ SomeImage.png ■ Documents ■ Library ■ Caches Tuesday, February 2, 2010 15
  • 38. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app ■ MyApp ■ MainWindow.nib ■ SomeImage.png ■ Documents ■ Library ■ Caches ■ Preferences Tuesday, February 2, 2010 15
  • 39. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app ■ MyApp ■ MainWindow.nib ■ SomeImage.png ■ Documents ■ Library ■ Caches ■ Preferences • Applications only read and write within their home directory Tuesday, February 2, 2010 15
  • 40. Home Directory Layout • Each app has its own set of directories • <Application Home> ■ MyApp.app ■ MyApp ■ MainWindow.nib ■ SomeImage.png ■ Documents ■ Library ■ Caches ■ Preferences • Applications only read and write within their home directory • Backed up by iTunes during sync (mostly) Tuesday, February 2, 2010 15
  • 41. File Paths in Your Application Tuesday, February 2, 2010 16
  • 42. File Paths in Your Application // Basic directories NSString *homePath = NSHomeDirectory(); NSString *tmpPath = NSTemporaryDirectory(); Tuesday, February 2, 2010 16
  • 43. File Paths in Your Application // Basic directories NSString *homePath = NSHomeDirectory(); NSString *tmpPath = NSTemporaryDirectory(); // Documents directory NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsPath = [paths objectAtIndex:0]; Tuesday, February 2, 2010 16
  • 44. File Paths in Your Application // Basic directories NSString *homePath = NSHomeDirectory(); NSString *tmpPath = NSTemporaryDirectory(); // Documents directory NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsPath = [paths objectAtIndex:0]; // <Application Home>/Documents/foo.plist NSString *fooPath = [documentsPath stringByAppendingPathComponent:@“foo.plist”]; Tuesday, February 2, 2010 16
  • 45. Including Writable Files with Your App • Many applications want to include some starter data • But application bundles are code signed ■ You can’t modify the contents of your app bundle • To include a writable data file with your app... ■ Build it as part of your app bundle ■ On first launch, copy it to your Documents directory Tuesday, February 2, 2010 17
  • 47. Archiving Objects • Next logical step from property lists ■ Include arbitrary classes ■ Complex object graphs • Used by Interface Builder for NIBs Tuesday, February 2, 2010 19
  • 48. Making Objects Archivable • Conform to the <NSCoding> protocol Tuesday, February 2, 2010 20
  • 49. Making Objects Archivable • Conform to the <NSCoding> protocol // Encode an object for an archive - (void)encodeWithCoder:(NSCoder *)coder { [super encodeWithCoder:coder]; [coder encodeObject:name forKey:@“Name”]; [coder encodeInteger:numberOfSides forKey:@“Sides”]; } // Decode an object from an archive - (id)initWithCoder:(NSCoder *)coder { self = [super initWithCoder:coder]; name = [[coder decodeObjectForKey:@“Name”] retain]; numberOfSides = [coder decodeIntegerForKey:@“Side”]; } Tuesday, February 2, 2010 20
  • 50. Archiving & Unarchiving Object Graphs Tuesday, February 2, 2010 21
  • 51. Archiving & Unarchiving Object Graphs • Creating an archive NSArray *polygons = ...; NSString *path = ...; BOOL result = [NSKeyedArchiver archiveRootObject:polygons toFile:path]; Tuesday, February 2, 2010 21
  • 52. Archiving & Unarchiving Object Graphs • Creating an archive NSArray *polygons = ...; NSString *path = ...; BOOL result = [NSKeyedArchiver archiveRootObject:polygons toFile:path]; • Decoding an archive NSArray *polygons = nil; NSString *path = ...; polygons = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; Tuesday, February 2, 2010 21
  • 53. More on Archiving Objects • “Archives and Serializations Programming Guide for Cocoa” http://developer.apple.com/documentation/Cocoa/ Conceptual/Archiving/ Tuesday, February 2, 2010 22
  • 54. The Joy of SQLite Tuesday, February 2, 2010 23
  • 55. SQLite • Complete SQL database in an ordinary file • Simple, compact, fast, reliable • No server • Free/Open Source Software • Great for embedded devices ■ Included on the iPhone platform Tuesday, February 2, 2010 24
  • 56. When Not to Use SQLite • Multi-gigabyte databases • High concurrency (multiple writers) • Client-server applications • “Appropriate Uses for SQLite” http://www.sqlite.org/whentouse.html Tuesday, February 2, 2010 25
  • 57. SQLite C API Basics Tuesday, February 2, 2010 26
  • 58. SQLite C API Basics • Open the database int sqlite3_open(const char *filename, sqlite3 **db); Tuesday, February 2, 2010 26
  • 59. SQLite C API Basics • Open the database int sqlite3_open(const char *filename, sqlite3 **db); • Execute a SQL statement int sqlite3_exec(sqlite3 *db, const char *sql, int (*callback)(void*,int,char**,char**), void *context, char **error); Tuesday, February 2, 2010 26
  • 60. SQLite C API Basics • Open the database int sqlite3_open(const char *filename, sqlite3 **db); • Execute a SQL statement int sqlite3_exec(sqlite3 *db, const char *sql, int (*callback)(void*,int,char**,char**), void *context, char **error); // Your callback int callback(void *context, int count, char **values, char **columns); Tuesday, February 2, 2010 26
  • 61. SQLite C API Basics • Open the database int sqlite3_open(const char *filename, sqlite3 **db); • Execute a SQL statement int sqlite3_exec(sqlite3 *db, const char *sql, int (*callback)(void*,int,char**,char**), void *context, char **error); // Your callback int callback(void *context, int count, char **values, char **columns); • Close the database int sqlite3_close(sqlite3 *db); Tuesday, February 2, 2010 26
  • 62. Demo: Simple SQLite Tuesday, February 2, 2010 27
  • 63. More on SQLite • “SQLite in 5 Minutes Or Less” http://www.sqlite.org/quickstart.html • “Intro to the SQLite C Interface” http://www.sqlite.org/cintro.html Tuesday, February 2, 2010 28
  • 64. Core Data • Object-graph management and persistence framework ■ Makes it easy to save & load model objects ■ Properties ■ Relationships ■ Higher-level abstraction than SQLite or property lists • Available on the Mac OS X desktop • Now available on iPhone OS 3.0 Tuesday, February 2, 2010 29
  • 65. Two classes you should know about... Tuesday, February 2, 2010 30
  • 66. Two classes you should know about... • NSPredicate Tuesday, February 2, 2010 30
  • 67. Two classes you should know about... • NSPredicate ■ “Used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.” Tuesday, February 2, 2010 30
  • 68. Two classes you should know about... • NSPredicate ■ “Used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.” ■ -[NSPredicate predicateWithFormat:] Tuesday, February 2, 2010 30
  • 69. Two classes you should know about... • NSPredicate ■ “Used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.” ■ -[NSPredicate predicateWithFormat:] ■ Simple comparisons: Tuesday, February 2, 2010 30
  • 70. Two classes you should know about... • NSPredicate ■ “Used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.” ■ -[NSPredicate predicateWithFormat:] ■ Simple comparisons: ■ grade == “7” Tuesday, February 2, 2010 30
  • 71. Two classes you should know about... • NSPredicate ■ “Used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.” ■ -[NSPredicate predicateWithFormat:] ■ Simple comparisons: ■ grade == “7” ■ user.firstName like "Tom" Tuesday, February 2, 2010 30
  • 72. Two classes you should know about... • NSPredicate ■ “Used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.” ■ -[NSPredicate predicateWithFormat:] ■ Simple comparisons: ■ grade == “7” ■ user.firstName like "Tom" ■ “first contains [c]”chris” Tuesday, February 2, 2010 30
  • 73. Two classes you should know about... • NSPredicate ■ “Used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.” ■ -[NSPredicate predicateWithFormat:] ■ Simple comparisons: ■ grade == “7” ■ user.firstName like "Tom" ■ “first contains [c]”chris” ■ Many, many options: http://developer.apple.com/mac/library/documentation/cocoa/ Conceptual/Predicates/Articles/pSyntax.html Tuesday, February 2, 2010 30
  • 74. Two classes you should know about... Tuesday, February 2, 2010 31
  • 75. Two classes you should know about... • NSEntityDescription Tuesday, February 2, 2010 31
  • 76. Two classes you should know about... • NSEntityDescription ■ Used for inserting a new object into a Core Data Managed Object context Tuesday, February 2, 2010 31
  • 77. Two classes you should know about... • NSEntityDescription ■ Used for inserting a new object into a Core Data Managed Object context ■ - [NSEntityDescription insertNewObjectForEntityForName:inManagedObjectContext:] Tuesday, February 2, 2010 31
  • 78. Two classes you should know about... • NSEntityDescription ■ Used for inserting a new object into a Core Data Managed Object context ■ - [NSEntityDescription insertNewObjectForEntityForName:inManagedObjectContext:] ■ See the documentation! Tuesday, February 2, 2010 31
  • 79. Two classes you should know about... • NSEntityDescription ■ Used for inserting a new object into a Core Data Managed Object context ■ - [NSEntityDescription insertNewObjectForEntityForName:inManagedObjectContext:] ■ See the documentation! ■ http://developer.apple.com/mac/library/documentation/cocoa/ reference/CoreDataFramework/Classes/ NSEntityDescription_Class/NSEntityDescription.html Tuesday, February 2, 2010 31
  • 81. Your Application & The Cloud • Store & access remote data • May be under your control or someone else’s • Many Web 2.0 apps/sites provide developer API Tuesday, February 2, 2010 33
  • 82. “I made a location-based user-generated video blogging mashup... for pets!” Tuesday, February 2, 2010 34
  • 83. Integrating with Web Services • Non-goal of this class: teach you all about web services ■ Plenty of tutorials accessible, search on Google • Many are exposed via RESTful interfaces with XML or JSON ■ REpresentational State Transfer ■ Stateless interactions ■ Well defined client/server roles & interfaces ■ e.g. HTTP • High level overview of parsing these types of data Tuesday, February 2, 2010 35
  • 85. Options for Parsing XML • libxml2 ■ Tree-based: easy to parse, entire tree in memory ■ Event-driven: less memory, more complex to manage state ■ Text reader: fast, easy to write, efficient • NSXMLParser ■ Event-driven API: simpler but less powerful than libxml2 Tuesday, February 2, 2010 37
  • 86. More on Parsing XML • Brent Simmons, “libxml2 + xmlTextReader on Macs” http://inessential.com/?comments=1&postid=3489 ■ Includes example of parsing Twitter XML! • Big Nerd Ranch, “Parsing XML in Cocoa” http://weblog.bignerdranch.com/?p=48 ■ Covers the basics of NSXMLReader Tuesday, February 2, 2010 38
  • 88. JavaScript Object Notation • More lightweight than XML • Looks a lot like a property list ■ Arrays, dictionaries, strings, numbers • Open source json-framework wrapper for Objective-C Tuesday, February 2, 2010 40
  • 89. What does a JSON object look like? Tuesday, February 2, 2010 41
  • 90. What does a JSON object look like? { Tuesday, February 2, 2010 41
  • 91. What does a JSON object look like? { “instructor” : “Josh Shaffer”, Tuesday, February 2, 2010 41
  • 92. What does a JSON object look like? { “instructor” : “Josh Shaffer”, “students” : 60, Tuesday, February 2, 2010 41
  • 93. What does a JSON object look like? { “instructor” : “Josh Shaffer”, “students” : 60, “itunes-u” : true, Tuesday, February 2, 2010 41
  • 94. What does a JSON object look like? { “instructor” : “Josh Shaffer”, “students” : 60, “itunes-u” : true, “midterm-exam” : null, Tuesday, February 2, 2010 41
  • 95. What does a JSON object look like? { “instructor” : “Josh Shaffer”, “students” : 60, “itunes-u” : true, “midterm-exam” : null, “assignments” : [ “WhatATool”, Tuesday, February 2, 2010 41
  • 96. What does a JSON object look like? { “instructor” : “Josh Shaffer”, “students” : 60, “itunes-u” : true, “midterm-exam” : null, “assignments” : [ “WhatATool”, “HelloPoly”, Tuesday, February 2, 2010 41
  • 97. What does a JSON object look like? { “instructor” : “Josh Shaffer”, “students” : 60, “itunes-u” : true, “midterm-exam” : null, “assignments” : [ “WhatATool”, “HelloPoly”, “Presence” ] Tuesday, February 2, 2010 41
  • 98. What does a JSON object look like? { “instructor” : “Josh Shaffer”, “students” : 60, “itunes-u” : true, “midterm-exam” : null, “assignments” : [ “WhatATool”, “HelloPoly”, “Presence” ] } Tuesday, February 2, 2010 41
  • 99. Using json-framework • Reading a JSON string into Foundation objects Tuesday, February 2, 2010 42
  • 100. Using json-framework • Reading a JSON string into Foundation objects #import <JSON/JSON.h> Tuesday, February 2, 2010 42
  • 101. Using json-framework • Reading a JSON string into Foundation objects #import <JSON/JSON.h> // Get a JSON string from the cloud NSString *jsonString = ...; Tuesday, February 2, 2010 42
  • 102. Using json-framework • Reading a JSON string into Foundation objects #import <JSON/JSON.h> // Get a JSON string from the cloud NSString *jsonString = ...; // Parsing will result in Foundation objects // Top level may be an NSDictionary or an NSArray id object = [jsonString JSONValue]; Tuesday, February 2, 2010 42
  • 103. Using json-framework • Writing a JSON string from Foundation objects Tuesday, February 2, 2010 43
  • 104. Using json-framework • Writing a JSON string from Foundation objects // Create some data in your app Tuesday, February 2, 2010 43
  • 105. Using json-framework • Writing a JSON string from Foundation objects // Create some data in your app NSDictionary *dictionary = ...; // Convert into a JSON string before sending to the cloud Tuesday, February 2, 2010 43
  • 106. Using json-framework • Writing a JSON string from Foundation objects // Create some data in your app NSDictionary *dictionary = ...; // Convert into a JSON string before sending to the cloud jsonString = [dictionary JSONRepresentation]; Tuesday, February 2, 2010 43
  • 107. Demo: Flickr API with JSON Tuesday, February 2, 2010 44
  • 108. More on JSON • “JSON Parser/Generator for Objective-C” http://code.google.com/p/json-framework/ • “Introducing JSON” http://www.json.org/ Tuesday, February 2, 2010 45
  • 109. Apple Push Notification Service Tuesday, February 2, 2010 46
  • 111. Overview • Show badges, alerts and play sounds without app running Tuesday, February 2, 2010 47
  • 112. Overview • Show badges, alerts and play sounds without app running • Minimal server infrastructure needed Tuesday, February 2, 2010 47
  • 113. Overview • Show badges, alerts and play sounds without app running • Minimal server infrastructure needed • Preserves battery life: 1 versus n TCP/IP connections Apple Server Push Service Tuesday, February 2, 2010 47
  • 114. Using the Service Server Tuesday, February 2, 2010 48
  • 115. Using the Service What you need Server Tuesday, February 2, 2010 48
  • 116. Using the Service What you need Server Tuesday, February 2, 2010 48
  • 117. Using the Service What you need Server edu.stanford.cs193.app Tuesday, February 2, 2010 48
  • 118. Using the Service What you need Server edu.stanford.cs193.app Tuesday, February 2, 2010 48
  • 119. Using the Service What you do Apple Push Server Service Tuesday, February 2, 2010 49
  • 120. Using the Service 1. Register with the service Apple Push Chris’s iPhone Service Tuesday, February 2, 2010 50
  • 121. Using the Service Chris’s iPhone Server Tuesday, February 2, 2010 51
  • 122. Using the Service 2. Send token to your server Server Chris’s iPhone Tuesday, February 2, 2010 51
  • 123. Using the Service 3. Send notifications Apple Push Server Service Chris’s iPhone Tuesday, February 2, 2010 52
  • 124. Using the Service 3. Send notifications Apple Push JSON Service Server Chris’s iPhone Tuesday, February 2, 2010 52
  • 125. Using the Service 4. Receive notifications Apple Push Service Tuesday, February 2, 2010 53
  • 126. Using the Service 4. Receive notifications Apple Push JSON Service Tuesday, February 2, 2010 53
  • 127. Using the Service 1. Register with the service Apple Push Chris’s iPhone Service Tuesday, February 2, 2010 54
  • 128. Using the Service 1. Register with the service Apple Push Chris’s iPhone Service Tuesday, February 2, 2010 54
  • 129. Registering with the Service Application launch • UIKit API in UIApplication.h to register ■ Pass the types you want to receive -(void)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options { // Register this app on this device UIRemoteNotificationType myTypes = UIRemoteNotificationTypeSounds | UIRemoteNotificationTypeBadges; [application registerForRemoteNotificationTypes:myTypes]; } Tuesday, February 2, 2010 55
  • 130. Registering with the Service Delegate callbacks Tuesday, February 2, 2010 56
  • 131. Registering with the Service Delegate callbacks - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)token { // Phone home with device token } Tuesday, February 2, 2010 56
  • 132. Registering with the Service Delegate callbacks - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)token { // Phone home with device token } - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { // Oh noes! Check your Provisioning Profile on device and in Xcode } Tuesday, February 2, 2010 56
  • 133. Registering with the Service 96385da767191121a851963983fdac9bbdf74dcf6219ae14ed8d08228 Tuesday, February 2, 2010 57
  • 134. Registering with the Service The device token 96385da767191121a851963983fdac9bbdf74dcf6219ae14ed8d08228 Tuesday, February 2, 2010 57
  • 135. Registering with the Service The device token • Uniquely identifies device 96385da767191121a851963983fdac9bbdf74dcf6219ae14ed8d08228 Tuesday, February 2, 2010 57
  • 136. Registering with the Service The device token • Uniquely identifies device ■ Distinct from -[UIDevice deviceIdentifier] 96385da767191121a851963983fdac9bbdf74dcf6219ae14ed8d08228 Tuesday, February 2, 2010 57
  • 137. Registering with the Service The device token • Uniquely identifies device ■ Distinct from -[UIDevice deviceIdentifier] • Just call registration API again if token is needed 96385da767191121a851963983fdac9bbdf74dcf6219ae14ed8d08228 Tuesday, February 2, 2010 57
  • 138. Registering for Notifications Optional callbacks and methods • UIApplicationDelegate - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo Tuesday, February 2, 2010 58
  • 139. Registering for Notifications Optional callbacks and methods • UIApplicationDelegate - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo • UIApplication - (UIRemoteNotificationType)enabledRemoteNotificationTypes Tuesday, February 2, 2010 58
  • 140. Using the Service Chris’s iPhone Server Tuesday, February 2, 2010 59
  • 141. Using the Service 2. Send token to your server Server Chris’s iPhone Tuesday, February 2, 2010 59
  • 142. Using the Service 3. Send notifications Apple Push Server Service Chris’s iPhone Tuesday, February 2, 2010 60
  • 143. Using the Service 3. Send notifications Apple Push JSON Server Service Chris’s iPhone edu.s.cs193 Tuesday, February 2, 2010 60
  • 144. Sending Notifications { "aps" : { "alert" : "Jen: Sushi at 10?", "badge" : 1, "sound" : "Jingle.aiff" }, "acme1" : "conversation9964" } Tuesday, February 2, 2010 61
  • 145. Sending Notifications Message payload { "aps" : { "alert" : "Jen: Sushi at 10?", "badge" : 1, "sound" : "Jingle.aiff" }, "acme1" : "conversation9964" } Tuesday, February 2, 2010 61
  • 146. Sending Notifications Message payload • Strict RFC 4627 JSON { "aps" : { "alert" : "Jen: Sushi at 10?", "badge" : 1, "sound" : "Jingle.aiff" }, "acme1" : "conversation9964" } Tuesday, February 2, 2010 61
  • 147. Sending Notifications Message payload • Strict RFC 4627 JSON • 256 byte maximum { "aps" : { "alert" : "Jen: Sushi at 10?", "badge" : 1, "sound" : "Jingle.aiff" }, "acme1" : "conversation9964" } Tuesday, February 2, 2010 61
  • 148. Sending Notifications Message payload • aps dictionary reserved for the sound, badge or alert keys ■ All keys optional { "aps" : { "alert" : "Jen: Sushi at 10?", "badge" : 1, "sound" : "Jingle.aiff" }, "acme1" : "conversation9964" } • Rest of payload is for your app Tuesday, February 2, 2010 62
  • 149. Sending Notifications Message payload • aps dictionary reserved for the sound, badge or alert keys ■ All keys optional { "aps" : { "alert" : "Jen: Sushi at 10?", "badge" : 1, "sound" : "Jingle.aiff" }, "acme1" : "conversation9964" } • Rest of payload is for your app Tuesday, February 2, 2010 62
  • 150. Badges badge key, integer value • Positive integer ■ Or omit to remove { "aps" : { "badge" : 1 } } Tuesday, February 2, 2010 63
  • 151. Badges badge key, integer value • Positive integer ■ Or omit to remove { "aps" : { "badge" : 1 } } Tuesday, February 2, 2010 63
  • 152. Sounds sound key, string value • Either a filename in app bundle { ■ linear PCM "aps" : { "sound" : "Jingle.aiff" ■ MA4 } } ■ µLaw ■ aLaw • Or “default” • Vibration is automatic Tuesday, February 2, 2010 64
  • 153. Alerts alert key, string or dictionary value • Simplest form is just a string value { "aps" : { "alert" : "Jen: Sushi at 10?" } } • Can be localized (see documentation) • Can also customize the text on the view button ■ or omit it Tuesday, February 2, 2010 65
  • 154. Alerts alert key, string or dictionary value • Simplest form is just a string value { "aps" : { "alert" : "Jen: Sushi at 10?" } } • Can be localized (see documentation) • Can also customize the text on the view button ■ or omit it Tuesday, February 2, 2010 65
  • 155. Sending the Payload Send JSON that is stripped of whitespace { "aps" : { "alert" : "Jen: Sushi at 10?", "badge" : 1, 150 bytes "sound" : "Jingle1.aiff" }, "acme1" : "conversation9964" Tuesday, February 2, 2010 66
  • 156. Sending the Payload Send JSON that is stripped of whitespace {"aps":{"alert":"Jen: Sushi at 10?","badge": 1, "sound":"Jingle.aiff"},"acme1":"conversation 9964"} 96 bytes Tuesday, February 2, 2010 66
  • 157. Demo: Pushing to the Flickr app Tuesday, February 2, 2010 67
  • 158. NSUserDefaults recap (time permitting) Tuesday, February 2, 2010 68
  • 159. NSUserDefaults • Convenient way to store settings and lightweight state ■ Arrays, dictionaries, strings, numbers, dates, raw data ■ Settings bundles can be created so that user defaults can be set from Settings app ■ Internally stored as property lists Tuesday, February 2, 2010 69
  • 160. Reading & Writing User Defaults • Key-value store • Base methods accept and return objects for values + (NSUserDefaults *)standardUserDefaults; - (id)objectForKey:(NSString *)defaultName; - (void)setObject:(id)value forKey:(NSString *)defaultName; - (void)removeObjectForKey:(NSString *)defaultName; - (BOOL)synchronize; Tuesday, February 2, 2010 70
  • 161. Reading & Writing User Defaults • Many convenience methods that ‘box’ and ‘unbox’ the object ■ and perform type checking - (NSString *)stringForKey:(NSString *)defaultName; - (NSArray *)arrayForKey:(NSString *)defaultName; - (NSDictionary *)dictionaryForKey:(NSString *)defaultName; - (NSData *)dataForKey:(NSString *)defaultName; - (NSArray *)stringArrayForKey:(NSString *)defaultName; - (NSInteger)integerForKey:(NSString *)defaultName; - (float)floatForKey:(NSString *)defaultName; - (double)doubleForKey:(NSString *)defaultName; - (BOOL)boolForKey:(NSString *)defaultName; - (void)setInteger:(NSInteger)value forKey:(NSString *) defaultName; - (void)setFloat:(float)value forKey:(NSString *)defaultName; - (void)setDouble:(double)value forKey:(NSString *)defaultName; - (void)setBool:(BOOL)value forKey:(NSString *)defaultName; Tuesday, February 2, 2010 71
  • 162. -[NSUserDefaults synchronize] • Call [[NSUserDefaults standardUserDefaults] synchronize] to write changes to disk • Also loads external changes from disk (useful on Mac OS X) Tuesday, February 2, 2010 72
  • 163. More on NSUserDefaults • “User Defaults Programming Topics for Cocoa” http://developer.apple.com/mac/library/documentation/ Cocoa/Conceptual/UserDefaults/Tasks/UsingDefaults.html Tuesday, February 2, 2010 73
  • 164. Demo: NSUserDefaults and Settings Tuesday, February 2, 2010 74
  • 165. Recap • Property lists, NSUserDefaults ■ Quick & easy, but limited • Archived objects ■ More flexible, but require writing a lot of code • SQLite ■ Elegant solution for many types of problems • XML and JSON ■ Low-overhead options for talking to “the cloud” ■ Apple Push Notification Service pushes JSON from your server to devices Tuesday, February 2, 2010 75