在保存到 CoreData 之前检查数据中的 nil

Posted

技术标签:

【中文标题】在保存到 CoreData 之前检查数据中的 nil【英文标题】:Check for nil in data before saving to CoreData 【发布时间】:2016-06-20 01:07:28 【问题描述】:

我在下面有这段代码,运行时我希望它检查字段 itemName、itemNote 等是否为空,如果是则显示 UIAlertController 并阻止用户继续。我尝试使用的代码位于 saveTapped IBAction 函数下。目前,在运行时,它似乎绕过了所有检查并直接进入“if(item != nil) ”检查。

任何见解将不胜感激。

import UIKit
import CoreData

class AddEditViewController: UIViewController, NSFetchedResultsControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate 

var item : Item? = nil

@IBOutlet weak var itemName: UITextField!
@IBOutlet weak var itemNote: UITextField!
@IBOutlet weak var hoursPlayed: UITextField!
@IBOutlet weak var imageHolder: UIImageView!

let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

override func viewDidLoad() 
    super.viewDidLoad()

    if item != nil 
        itemName.text = item?.name
        itemNote.text = item?.note
        hoursPlayed.text = item?.hoursPlayed
        imageHolder.image = UIImage(data: (item?.image)!)
    


override func didReceiveMemoryWarning() 
    super.didReceiveMemoryWarning()


@IBAction func AddImage(sender: AnyObject) 
    let pickerController = UIImagePickerController()
    pickerController.delegate = self
    pickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    pickerController.allowsEditing = true

    self.presentViewController(pickerController, animated: true, completion: nil)


@IBAction func addImageFromCamera(sender: AnyObject) 
    let pickerController = UIImagePickerController()
    pickerController.delegate = self
    pickerController.sourceType = UIImagePickerControllerSourceType.Camera
    pickerController.allowsEditing = true

    self.presentViewController(pickerController, animated: true, completion: nil)


func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) 
    self.dismissViewControllerAnimated(true, completion: nil)

    self.imageHolder.image = image


@IBAction func saveTapped(sender: AnyObject) 

    var nameMissing = ""

    if itemName == nil 
        nameMissing = "name"
        print("item missing")
    
    else if itemNote == nil 
        nameMissing = "note"
        print("note missing")
    
    else if hoursPlayed == nil 
        nameMissing = "hours played"
        print("hours played missing")
    
    else if imageHolder == nil 
        nameMissing = "image"
        print("image missing")
    

    if (itemName == nil || itemNote == nil || hoursPlayed == nil || imageHolder == nil) 
        let missingDetailsAlertController = UIAlertController(title: "Alert", message: "Complete field for \(nameMissing).", preferredStyle: UIAlertControllerStyle.Alert)
        missingDetailsAlertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(missingDetailsAlertController, animated: true, completion: nil)
        return
    

    if(item != nil) 
        editItem()
     else 
        createNewItem()
    
    dismissViewController()


@IBAction func cancelTapped(sender: AnyObject) 
    dismissViewController()


func dismissViewController() 
    navigationController?.popViewControllerAnimated(true)


func createNewItem() 
    let entityDescription = NSEntityDescription.entityForName("item", inManagedObjectContext: moc)

    let item = Item(entity: entityDescription!, insertIntoManagedObjectContext: moc)

    item.name = itemName.text
    item.note = itemNote.text
    item.hoursPlayed = hoursPlayed.text
    item.image = UIImagePNGRepresentation(imageHolder.image!)

    do 
        try moc.save()
     catch 
        print("Create Save Failed.")
        return
    


func editItem() 
    item?.name = itemName.text
    item?.note = itemNote.text
    item?.hoursPlayed = hoursPlayed.text
    item!.image = UIImagePNGRepresentation(imageHolder.image!)

    do 
        try moc.save()
     catch 
        print("Edit Save Failed.")
        return
    


【问题讨论】:

【参考方案1】:

您应该检查textFieldstext 属性而不是nil。 试试这个:

if let name = itemName.text where name.characters.count > 0 
   //show your alert
 else if let note = itemNote.text where note.characters.count > 0 
  //show your alert
 else if let hours = hoursPlayed.text where hours.characters.count > 0 
  //show your alert
 else if let image = imageHolder.image 
   //show your alert

如果您想在没有警报的情况下访问该值,那么您也可以尝试 UITextFields

let name = itemName.text ?? ""
let note = itemNote.text ?? ""
let hours = hoursPlayed.text ?? ""

【讨论】:

啊,谢谢,检查图像,我需要使用 CGSize 或其他什么吗? CGSize 是为了什么?没看懂你的意思,能详细点吗? 我正在尝试寻找一种方法来检测图像是否存在。【参考方案2】:

无需每次都做额外的代码

使用这个简单的代码检查空字符串

let bananaName = "       "  //Empty String

let mango = "Mango"


//Make file for this function and call like my example below return Boolean value for check the value

//Function
struct Checker 

    static func isEmptyfor(content:String) -> Bool? 

        guard content.trimString.isEmpty else 
            print("Not Empty")
            return true
        

        print("Empty")
        return false
    



// String Extenion here for Validate trim String
extension String 
    var trimString:String 
       return  self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    


//***Final Code here for use this Only for check your string

//Call Function here Like This
//##exp 1
if Checker.isEmptyfor(bananaName)! 
    print("Not Empty")
   //Do something here

else
    print("Empty")


//##exp 2
if Checker.isEmptyfor(mango)! 
    print("Not Empty")
  //Do something here

else
    print("Empty")

Playground 内代码的输出

【讨论】:

以上是关于在保存到 CoreData 之前检查数据中的 nil的主要内容,如果未能解决你的问题,请参考以下文章

RestKit CoreData 0.20.3 - 映射完成后保存 MOC 之前的额外检查

保存到数据库帖子,但在检查 Ruby on Rails 中的 http 请求之前

在保存到核心数据之前将字符串与 NSPredicate 进行比较

CoreData:将数据保存到上下文

如何在 Core Data 中正确保存?

在插入之前检查 sqlite 中的重复项(核心数据)