如何在swift中使用字符串获取

时间:2016-07-02 21:15:33

标签: xcode swift core-data nsmanagedobject nsfetchrequest

我只是想知道如何使用搜索条码在Swift中使用Core Data进行获取。我基本上将条形码传递给static func方法,但我怎样才能使用它从核心数据中获取数据?

以下是检测到的条形码:

func barcodeDetected(code: String) {

    // Let the user know we've found something.

    let alert = UIAlertController(title: "Found a Barcode!", message: code, preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Search", style: UIAlertActionStyle.Destructive, handler: { action in

        // Remove the spaces.

        let trimmedCode = code.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

        // EAN or UPC?
        // Check for added "0" at beginning of code.

        let trimmedCodeString = "\(trimmedCode)"
        var trimmedCodeNoZero: String

        if trimmedCodeString.hasPrefix("0") && trimmedCodeString.characters.count > 1 {
            trimmedCodeNoZero = String(trimmedCodeString.characters.dropFirst())

            // Send the doctored barcode
            ProductDetailsViewController.searchCode(trimmedCodeNoZero)
        } else {

            // Send the doctored barcode
            ProductDetailsViewController.searchCode(trimmedCodeString)

        }

        self.navigationController?.popViewControllerAnimated(true)
    }))

    self.presentViewController(alert, animated: true, completion: nil)
}

我的产品类别:

import UIKit
import Foundation
import CoreData


class ProductDetailsViewController: UIViewController, NSFetchedResultsControllerDelegate {

    @IBOutlet weak var productLabel: UILabel!
    @IBOutlet weak var priceLabel: UILabel!

    @IBAction func addProduct(sender: AnyObject) {
        let AppDel = UIApplication.sharedApplication().delegate as? AppDelegate
        let context:NSManagedObjectContext = (AppDel?.managedObjectContext)!

        let ent = NSEntityDescription.entityForName("Products", inManagedObjectContext: context)

        var newProduct = ProductItem(entity: ent!, insertIntoManagedObjectContext: context)
        newProduct.title = productLabel.text
        //newProduct.price = priceLabel.text

        /*context.save(nil)
        print(newProduct)
        print("Object Saved")*/

    }

    private(set) var PRODUCT_NAME = ""
    private(set) var PRODUCT_PRICE = ""
    private var menuItems:[ProductItem] = []

    static func searchCode(codeNumber: String) -> String{

        let barcodeNumber = codeNumber
        return barcodeNumber

    }
        deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        productLabel.text = "Scan a Product"
        priceLabel.text = ""

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "setLabels:", name: "ProductNotification", object: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }   

}

我已成功将这些项目添加到Core Data中,并且能够将所有项目加载到我的应用程序的表格中。现在扫描条形码后,我希望能够只使用条形码加载产品,并且我会卡在那部分上。正如你可以看到我的静态趣味searchCode从barcodeDetected接收条形码,但接下来我应该怎么做才能获取它?谢谢。

编辑:

核心数据实体

import Foundation
import CoreData
@objc(ProductItem)

class ProductItem: NSManagedObject{
    @NSManaged var barcodeNum:String?
    @NSManaged var box_height:NSNumber?
    @NSManaged var box_length:NSNumber?
    @NSManaged var box_width:NSNumber?
    @NSManaged var price:NSNumber?
    @NSManaged var sku:String?
    @NSManaged var weight:NSNumber?
    @NSManaged var title:String?


}

1 个答案:

答案 0 :(得分:0)

要获取正确的ProductItem,您需要使用谓词(请参阅Apple文档here)。在你的情况下,你可以使用这样的东西:

let AppDel = UIApplication.sharedApplication().delegate as? AppDelegate
let context:NSManagedObjectContext = (AppDel?.managedObjectContext)!
let fetchRequest = NSFetchRequest(entityName: "ProductItem")
fetchRequest.predicate = NSPredicate(format: "barcodeNum == %@",codeNumber)
let results = try! context.executeFetchRequest(fetchRequest) as! [ProductItem]
if results.count > 0 { // great, you found (at least one) matching item
    let scannedProduct = results[0]
    // from here you can access the attributes of the product
    // such as title, price, sku, etc.
    ...
} else { // not found
    ...
}

请注意,为了简洁起见,我使用try!,但在实践中,您应该使用正确的do ... catch语法并处理任何错误。

我不清楚你在ProductDetailsViewController中使用静态函数的原因;一种常见的方法是在barcodeDetected方法中使用上述提取,然后转到ProductDetailsViewController传递相关ProductItem以进行显示/编辑或其他任何操作。或者,如果找不到产品,则显示警报视图。