如何使用 swift 中的字符串获取
How to fetch using string in swift
我只是想知道如何使用搜索到的条形码来使用 Swift 中的核心数据进行提取。我基本上是将条形码传递给 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)
}
我的产品Class:
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()
}
}
我已经成功地将项目添加到核心数据中,并且能够将所有项目加载到我的应用程序中的 table 中。现在扫描条形码后,我希望能够用条形码加载产品,但我被困在了那个部分。如您所见,我的 static fun 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?
}
要获取正确的 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
for display/editing 或其他。或者在未找到产品时显示警报视图。
我只是想知道如何使用搜索到的条形码来使用 Swift 中的核心数据进行提取。我基本上是将条形码传递给 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)
}
我的产品Class:
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()
}
}
我已经成功地将项目添加到核心数据中,并且能够将所有项目加载到我的应用程序中的 table 中。现在扫描条形码后,我希望能够用条形码加载产品,但我被困在了那个部分。如您所见,我的 static fun 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?
}
要获取正确的 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
for display/editing 或其他。或者在未找到产品时显示警报视图。