我最近因为我的代码可读性和清洁度而苦苦挣扎,这是我经常遇到的问题。以下方法运行正常,并完成我需要的一切。
我已经标出了我的问题所在的界限:
/**
Creates a new `Group` and adds the currently logged in user as the `groupOwner`.
- parameter name: The name of the group
- parameter completion: Called when the save request has completed passing back the newly saved `Group`. If an error occured it will be returned and `group` will be `nil`.
*/
static func createNewGroup(name: String, completion:(group: Group?, error: NSError?) -> ()) {
// Instantiate our new `Group`
let newGroup = Group()
newGroup.groupName = name
newGroup.groupOwner = User.currentUser()!
newGroup.saveInBackgroundWithBlock { (success, error) in
// There was some problem saving the newGroup so return the error
if let err = error {
completion(group: nil, error: err)
}
// The newGroup was saved OK.
else {
// Now, since we've successfully saved the newGroup, we can append that to our current user.
User.currentUser()!.ownedGroups.append(newGroup)
//
// HERE IS MY QUESTION
//
// Next up is the save the current user since he/she has been modified.
User.currentUser()?.saveInBackgroundWithBlock({ (success, error) in
// If there was some error saving the user, then we should delete the newGroup so it isn't hanging around in the db.
if let err = error {
newGroup.deleteInBackground()
completion(group: nil, error: err)
}
// Everything went OK some return our recently saved newGroup
else {
completion(group: newGroup, error: nil)
}
})
}
}
}
我的问题是我应该使用saveInBackgroundWithBlock
保存当前用户吗?这个方法看起来比上面的嵌套块更优雅和正确:
/**
Creates a new `Group` and adds the currently logged in user as the `groupOwner`.
- parameter name: The name of the group
- parameter completion: Called when the save request has completed passing back the newly saved `Group`. If an error occured it will be returned and `group` will be `nil`.
*/
static func createNewGroup(name: String, completion:(group: Group?, error: NSError?) -> ()) {
// Instantiate our new `Group`
let newGroup = Group()
newGroup.groupName = name
newGroup.groupOwner = User.currentUser()!
newGroup.saveInBackgroundWithBlock { (success, error) in
// There was some problem saving the newGroup so return the error
if let err = error {
completion(group: nil, error: err)
}
// The newGroup was saved OK.
else {
// Now, since we've successfully saved the newGroup, we can append that to our current user.
User.currentUser()!.ownedGroups.append(newGroup)
// Save and return
User.currentUser()?.saveInBackground()
completion(group: newGroup, error: nil)
}
}
}
但是,我担心在某些随机边缘情况下,在后台保存给用户不会完成。然后我会在我的数据库中挂起这个Group
对象,用户下次加载应用时也不会看到它。
我的恐惧在这里是假的还是我原来的方法是构建这个功能的正确方法?
答案 0 :(得分:0)
我认为你原来的方法是正确的方法。 还有一件事,你需要在后台保存时显示一个activityindicator。