Parse Objects and Queries

Exclusive offer: get 50% off this eBook here
Application Development with Parse using iOS SDK

Application Development with Parse using iOS SDK — Save 50%

Develop the backend of your applications instantly using Parse iOS SDK with this book and ebook

$14.99    $7.50
by Bhanu Birani | October 2013 | Open Source

In this article by Bhanu Birani, author of Application Development with Parse using iOS SDK, we will learn how Parse helps you to manage your complete backend structure for mobile applications and discard the requirement of developing complex server-side code and their maintenance. Parse provides you with the database structures in the form of objects. It saves all your data in the form of objects and will return the same object while retrieving back from Parse.

(For more resources related to this topic, see here.)

In this article, we will learn how to work with Parse objects along with writing queries to set and get data from Parse.

Every application has a different and specific Application ID associated with the Client Key, which remains same for all the applications of the same user.

Parse is based on object-oriented principles. All the operations on Parse will be done in the form of objects. Parse saves your data in the form of objects you send, and helps you to fetch the data in the same format again. In this article, you will learn about objects and operations that can be performed on Parse objects.

Parse objects

All the data in Parse is saved in the form of PFObject. When you fetch any data from Parse by firing a query, the result will be in the form of PFObject. The detailed concept of PFObject is explained in the following section.

PFObject

Data stored on Parse is in the form of objects and it's developed around PFObject. PFObject can be defined as the key-value (dictionary format) pair of JSON data. The Parse data is schemaless, which means that you don't need to specify ahead of time what keys exist on each PFObject. Parse backend will take care of storing your data simply as a set of whatever key-value pair you want.

Let's say you are tracking the visited count of the username with a user ID using your application. A single PFObject could contain the following code:

visitedCount:1122, userName:"Jack Samuel", userId:1232333332

Parse accepts only string as Key. Values can be strings, numbers, Booleans, or even arrays, and dictionaries—anything that can be JSON encoded.

The class name of PFObject is used to distinguish different sorts of data. Let's say you call the visitedCounts object of the user. Parse recommends you to write your class name NameYourClassLikeThis and nameYourKeysLikeThis just to provide readability to the code. As you have seen in the previous example, we have used visitedCounts to represent the visited count key.

Operations on Parse objects

You can perform save, update, and delete operations on Parse objects. Following is the detailed explanation of the operations that can be performed on Parse objects.

Saving objects

To save your User table on the Parse Cloud with additional fields, you need to follow the coding convention similar to the NSMutableDictionary method. After updating the data you have to call the saveInBackground method to save it on the Parse Cloud. Here is the example that explains how to save additional data on the Parse Cloud:

PFObject *userObject = [PFObject currentUser];
[userObject setObject:[NSNumber numberWithInt:1122]
forKey:@"visitedCount"];
[userObject setObject:@"Jack Samuel" forKey:@"userName"];
[userObject setObject:@"1232333332" forKey:@"userId"];
[userObject saveInBackground];

Just after executing the preceding piece of code, your data is saved on the Parse Cloud. You can check your data in Data Browser of your application on Parse. It should be something similar to the following line of code:

objectId: "xWMyZ4YEGZ", visitedCount: 1122, userName: "Jack
Samuel", userId: "1232333332",
createdAt:"2011-06-10T18:33:42Z", updatedAt:"2011-06-10T18:33:42Z"

There are two things to note here:

  • You don't have to configure or set up a new class called User before running your code. Parse will automatically create the class when it first encounters it.
  • There are also a few fields you don't need to specify, those are provided as a convenience:
    • objectId is a unique identifier for each saved object.
    • createdAt and updatedAt represent the time that each object was created and last modified in the Parse Cloud. Each of these fields is filled in by Parse, so they don't exist on PFObject until a save operation has completed.

    You can provide additional logic after the success or failure of the callback operation using the saveInBackgroundWithBlock or saveInBackgroundWithTarget:selector: methods provided by Parse:

    [userObject saveInBackgroundWithBlock:^(BOOL
    succeeded, NSError *error) {
    if (succeeded)
    NSLog(@"Success");
    else
    NSLog(@"Error %@",error);
    }];

Fetching objects

To fetch the saved data from the Parse Cloud is even easier than saving data. You can fetch the data from the Parse Cloud in the following way.

You can fetch the complete object from its objectId using PFQuery. Methods to fetch data from the cloud are asynchronous. You can implement this either by using block-based or callback-based methods provided by Parse:

PFQuery *query = [PFQuery queryWithClassName:@"GameScore"]; // 1
[query getObjectInBackgroundWithId:@"xWMyZ4YEGZ" block:^(PFObject
*gameScore, NSError *error) { //2
// Do something with the returned PFObject in the gameScore
variable.

int score = [[gameScore objectForKey:@"score"] intValue];
NSString *playerName = [gameScore objectForKey:@"playerName"];
//3
BOOL cheatMode = [[gameScore objectForKey:@"cheatMode"]
boolValue];
NSLog(@"%@", gameScore);
}];
// The InBackground methods are asynchronous, so the code written
after this will be executed
// immediately. The codes which are dependent on the query result
should be moved
// inside the completion block above.

Lets analyze each line in here, as follows:

  • Line 1: It creates a query object pointing to the class name given in the argument.
  • Line 2: It calls an asynchronous method on the query object created in line 1 to download the complete object for objectId, provided as an argument. As we are using the block-based method, we can provide code inside the block, which will execute on success or failure.
  • Line 3: It reads data from PFObject that we got in response to the query.

Parse provides some common values of all Parse objects as properties:

NSString *objectId = gameScore.objectId;
NSDate *updatedAt = gameScore.updatedAt;
NSDate *createdAt = gameScore.createdAt;

To refresh the current Parse object, type:

[myObject refresh];

This method can be called on any Parse object, which is useful when you want to refresh the data of the object. Let's say you want to re-authenticate a user, so you can call the refresh method on the user object to refresh it.

Saving objects offline

Parse provides you with the functions to save your data when the user is offline. So when the user is not connected to the Internet, the data will be saved locally in the objects, and as soon as the user is connected to the Internet, data will be saved automatically on the Parse Cloud. If your application is forcefully closed before establishing the connection, Parse will try again to save the object next time the application is opened. For such operations, Parse provides you with the saveEventually method, so that you will not lose any data even when the user is not connected to the Internet. Eventually all calls are executed in the order the request is made. The following code demonstrates the saveEventually call:

// Create the object.
PFObject *gameScore = [PFObject objectWithClassName:@"GameScore"];
[gameScore setObject:[NSNumber numberWithInt:1337]
forKey:@"score"];
[gameScore setObject:@"Sean Plott" forKey:@"playerName"];
[gameScore setObject:[NSNumber numberWithBool:NO]
forKey:@"cheatMode"];
[gameScore saveEventually];

Summary

In this article, we explored Parse objects and the way to query the data available on Parse.

We started by exploring Parse objects and the ways to save these objects on the cloud.

Finally, we learned about the queries which will help us to fetch the saved data on Parse.

Resources for Article:


Further resources on this subject:


Application Development with Parse using iOS SDK Develop the backend of your applications instantly using Parse iOS SDK with this book and ebook
Published: October 2013
eBook Price: $14.99
Book Price: $24.99
See more
Select your format and quantity:

About the Author :


Bhanu Birani

Bhanu Birani has four years of experience in the software industry and a lifetime association with the technical industry. After years of programming in different programming languages, he started developing applications for iOS devices. He started software development during his college years and was really interested in learning new technologies in the market. He then joined a software company and started developing games for them, focusing on artificial intelligence development in games.

Books From Packt


iOS Development using MonoTouch Cookbook
iOS Development using MonoTouch Cookbook

Instant Passbook App Development for iOS How-to [Instant]
Instant Passbook App Development for iOS How-to [Instant]

Corona SDK application design
Corona SDK application design

Corona SDK Mobile Game Development: Beginner's Guide
Corona SDK Mobile Game Development: Beginner's Guide

Developing Mobile Games with Moai SDK
Developing Mobile Games with Moai SDK

iOS 5 Essentials
iOS 5 Essentials

Unity iOS Game Development Beginners Guide
Unity iOS Game Development Beginners Guide

Marmalade SDK Mobile Game Development Essentials
Marmalade SDK Mobile Game Development Essentials


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
i
d
a
D
E
8
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software