ParseのiOSのドキュメントを読んでみたメモ(1) #ハツカソン

ParseのiOSのドキュメントを読んでみたメモ(1) #ハツカソンParseはちゃんと使おうと思いながら、ぜんぜん手を付けられないでいたので、 #ハツカソン という機会を利用して一通り読んでみた。気になったところをメモしていく。個人のメモレベルの記事です。メモはObjective-CとSwiftが混在します(勢いで書いているので、目に入ったものをメモ)。とりあえず眺めていけば、何ができて何ができないかの感覚がつかめるから、書くとき早く書けるはず!



Retrieving Objects

  • 基本オブジェクトはPFObject
  • 取得したオブジェクトを最新の状態にしたいときは、myObject.refresh()

The Local Database

  • 一時的に端末に保存しておきたい情報はローカルデータベスを利用できる。
    • [Parse enableLocalDatastore]で、ローカルデータベースを有効化できる。
    • [Parse setApplicationId:clientKey:]の前に記述する。
    • gameScore.pinInBackground()で保存できる。
    • クラウドから同じデータを持ってきたら自動的にローカルのデータは更新される。

Retrieving Objects from the Local Datastore

  • ローカルデータベースから情報を取得する。
let query = PFQuery(className:"GameScore")
  (task: BFTask!) -> AnyObject! in
  if task.error != nil {
      // There was an error.
      return task
  // task.result will be your game score
  return task

Unpinning Objects

[gameScore unpinInBackground];

Saving Objects Offline

If you don’t need to know when the save has finished, you can use saveEventually instead. The advantage is that if the user currently doesn’t have a network connection, saveEventually will store the update on the device until a network connection is re-established.




Deleting Objects


Relational Data

// Create the post
var myPost = PFObject(className:"Post")
myPost["title"] = "I'm Hungry"
myPost["content"] = "Where should we go for lunch?"
// Create the comment
var myComment = PFObject(className:"Comment")
myComment["content"] = "Let's do Sushirrito."
// Add a relation between the Post and Comment
myComment["parent"] = myPost
// This will save both myPost and myComment

By default, when fetching an object, related PFObjects are not fetched.


var post = myComment["parent"] as PFObject
post.fetchIfNeededInBackgroundWithBlock {
  (post: PFObject!, error: NSError!) -> Void in
  let title = post["title"] as NSString
  // do something with your title variable
  • PFRelationを使うことで、many-to-manyを表現できる
  • ただ、PFRelationのリストは、取得時点ではダウンロードされていない。ダウンロードするには以下のようにする。
[[relation query] findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
  if (error) {
     // There was an error
  } else {
    // objects has all the Posts the current user liked.

Data types

  • PFObjects should not exceed 128 kilobytes in size.


Specifying Constrains with NSPredicate

Simple comparisons such as =, !=, <, >, <=, >=, and BETWEEN with a key and a constant.
Containment predicates, such as x IN {1, 2, 3}.
Key-existence predicates, such as x IN SELF.
BEGINSWITH expressions.
Compound predicates with AND, OR, and NOT.
Sub-queries with "key IN %@", subquery.
The following types of predicates are not supported:

Aggregate operations, such as ANY, SOME, ALL, or NONE.
Regular expressions, such as LIKE, MATCHES, CONTAINS, or ENDSWITH.
Predicates comparing one key to another.
Complex predicates with many ORed clauses.
  • whereKey:notEqualTo:
  • whereKey:greaterThan:
  • limit

Query Constraints


var query = PFQuery(className:"GameScore")
query.whereKey("playerEmail", equalTo:"")
query.getFirstObjectInBackgroundWithBlock {
  (object: PFObject!, error: NSError!) -> Void in
  if object != nil {
    NSLog("The getFirstObject request failed.")
  } else {
    // The find succeeded.
    NSLog("Successfully retrieved the object.")
  • skipで最初の幾つかを対象から外す。
  • [query orderByAscending:@"score"]などが使える。便利。
    • [query addAscendingOrder:@"score"]などでソートを追加できる。
  • comparisons
    • whereKey:lessThan:
    • whereKey:lessThanOrEqualTo: などあり。
  • containedIn:@[@"Jonathan Walsh", @"Dario Wunsh"]なども便利。


PFQuery *teamQuery = [PFQuery queryWithClassName:@"Team"];
[teamQuery whereKey:@"winPct" greaterThan:@(0.5)];
PFQuery *userQuery = [PFQuery queryForUser];
[userQuery whereKey:@"hometown" matchesKey:@"city" inQuery:teamQuery];
[userQuery findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
    // results will contain users with a hometown team with a winning record

You can restrict the fields returned by calling selectKeys: with an NSArray of keys. To retrieve documents that contain only the score and playerName fields (and also special built-in fields such as objectId, createdAt, and updatedAt):


You may also like...