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

January 20, 2015

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

ParseのiOSドキュメントを初めて上からざっと読んでるけど、すごい楽しいこれ。なんでもっと早くから手を付けていなかったんだ><

Objects

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”) query.fromLocalDatastore() query.getObjectInBackgroundWithId(“xWMyZ4YEGZ”).continueWithBlock({ (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.

へ〜。saveEventuallyをしておくと、saveできるまで何度もトライしてくれる。そして、保存処理を命令した順にやってくれる。

Counters

incrementKey:incrementKey:byAmount:を利用することでカウンターも簡単に表現。

Deleting Objects

delete系のメソッドでオブジェクトを消す。remove系のメソッドでフィールドを消す。

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 myComment.saveInBackground()

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

Fetchするときはこうする。

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.

Queries

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

求めるものがひとつと決まっているなら、getFirstObject系のメソッドを使う。

var query = PFQuery(className:“GameScore”) query.whereKey(“playerEmail”, equalTo:“dstemkoski@example.com”) 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"]なども便利。 notContainedInなどもある。この辺り正しくは、whereKey:notContainedIn:

クエリを重ねるとか。

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):


Profile picture

Written by morizotter who lives and works in Tokyo building useful things. You should follow them on Twitter