14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Closure を使って幸せ Parse 生活

Last updated at Posted at 2014-06-16

いちいちfindObjects...とか打つの面倒だしViewControllerが汚くなるのでラッピングしましょう。
それに、(objects as PFObject[]!).map {...}が美しくないです。

Message.swift
class Message {
    class func findAllByUserWithBlock (user: PFObject!, callback: (PFObject[]!)->()) {
        let query = PFQuery(className: "Message")
        query.whereKey("user", equalTo: user)
        query.findObjectsInBackgroundWithBlock {(objects : AnyObject[]!, error: NSError!) in
            if (objects.count > 0) {
                callback(objects as PFObject[]!)
            }
        }
    }
}
HogeViewController.swift
let user = PFUser.currentUser()
Message.findAllByUserWithBlock(user) {(messages: PFObject[]!) in
    self.messages = messages.map {(message: PFObject!) in JSQMessage(text: message["text"] as String, sender: message["sender"] as String, date: message.createdAt)}
}

まあまあ心が洗われる文法になりました。
PFObjectもラッピングしてあげればas String[""]も不要になりますね。
面倒くさいです。

ちなみにブロックはrubyのごとく()の外に出して呼ぶことが出来ます。
jQueryでよく見るような})を沢山見なくてすみますね。

PFUserも悲しい書き方がたくさん出来てしまうので、extension使って汚いコードを押し込みましょう。

14
14
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?