Pass the received strings from another table controller

综合技术 2017-11-15

I am building a quite simple product ordering app. This is a tabbed application being, Product List, Order List and settings. From the Product List (coredata parsed from remote csv file) I can search then select a row, which then pops an alert view to add desired quantity to textfield and then on "ADD" button in alertview I can segue with the four strings (Productcode, Detail, Quantity(from alertview) and barcode) to the Order List View controller. This is where im having trouble! I can print the four strings in console at the point of being recieved by OrderList, but I'm stuck for a way to pass those strings into My NSObject model in order to display and persist them in the labels of the tableviewcell.

Here is my OrderProduct.swift file:

import Foundation
import UIKit

class OrderProduct: NSObject, NSCoding {

var uuid: String = NSUUID().UUIDString
var productcode:String = ""
var detail:String = ""
var quantity:String = ""
var barcode:String = ""
var inOrderList = false

func encodeWithCoder(coder: NSCoder) {
    coder.encodeObject(uuid, forKey: "uuid")
    coder.encodeObject(productcode, forKey: "productcode")
    coder.encodeObject(detail, forKey: "detail")
    coder.encodeObject(quantity, forKey: "quantity")
    coder.encodeObject(barcode, forKey: "barcode")
    coder.encodeBool(inOrderList, forKey: "inOrderList")
}
required init?(coder decoder: NSCoder) {
    super.init()

    if let archivedUuid = decoder.decodeObjectForKey("uuid") as? String {
        uuid = archivedUuid
    }

    if let archivedProductcode = decoder.decodeObjectForKey("productcode") as? String {
        productcode = archivedProductcode
    }

    if let archivedDetail = decoder.decodeObjectForKey("detail") as? String {
        detail = archivedDetail
    }

    if let archivedQuantity = decoder.decodeObjectForKey("quantity") as? String {
        quantity = archivedQuantity
    }

    if let archivedBarcode = decoder.decodeObjectForKey("barcode") as? String {
        barcode = archivedBarcode
    }

    inOrderList = decoder.decodeBoolForKey("inOrderList")
}
init(productcode: String, detail: String, quantity: String, barcode: String) {
    super.init()

    self.productcode = productcode
    self.detail = detail
    self.quantity = quantity
    self.barcode = barcode
}
}

And here is my OrderViewController.swift file:

import Foundation
import UIKit

//MARK: - Class
class TestOrderViewController: UITableViewController{

required init?(coder decoder: NSCoder) {
    //print("init OrderViewController")
    super.init(coder: decoder)

    loadOrderProducts()
    }

    deinit {
}

//MARK: - Product Vars
    var passedProductcode = String()     //String is recieved here!
    var passedDetail = String()          //String is recieved here!
    var passedQuantity = String()        //String is recieved here!
    var passedBarcode = String()         //String is recieved here!

    var orderProducts = [OrderProduct]() //My Object model...

//MARK: - ViewDidLoad
override func viewDidLoad() {
    super.viewDidLoad()
    title = "Order List"

    orderProducts.productcode = passedProductcode //Trying to pass them but
    orderProducts.detail = passedDetail           //errors with "Value of type
    orderProducts.quantity = passedQuantity       //'[OrderProduct]' has no
    orderProducts.barcode = passedBarcode         //member 'productcode'?

    tableView.estimatedRowHeight = 80.0
    tableView.rowHeight = UITableViewAutomaticDimension
    }

// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // Return the number of rows in the section.

    return orderProducts.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("OrderCell", forIndexPath: indexPath) as! OrderTableViewCell
    let orderProduct = orderProducts[indexPath.row]
    cell.productcodeLabel.text = orderProduct.productcode
    cell.detailLabel.text = orderProduct.detail
    cell.quantityLabel.text = "X (orderProduct.quantity)"
    cell.barcodeLabel.text = orderProduct.barcode

    return cell
}

private func loadOrderProducts() {
    if let filePath = pathForOrderProducts() where NSFileManager.defaultManager().fileExistsAtPath(filePath) {
        if let archivedOrderProducts = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? [OrderProduct] {
            orderProducts = archivedOrderProducts
        }
    }
}

private func pathForOrderProducts() -> String? {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)

    if let documents = paths.first, let documentsURL = NSURL(string: documents) {
        return documentsURL.URLByAppendingPathComponent("orderProducts.plist").path
    }
    return nil
}

private func saveOrderProducts() {
    if let filePath = pathForOrderProducts() {
        NSKeyedArchiver.archiveRootObject(orderProducts, toFile: filePath)
        }
    }
}

Could somebody please guide me to what I am missing?

Your orderProducts
property in TestOrderViewController
is an Array of OrderProduct
so, when you try to do

cell.productcodeLabel.text = orderProducts.productcode //passedProductcode
cell.detailLabel.text = orderProducts.detail //passedDetail
cell.quantityLabel.text = "X (orderProducts.quantity/*passedQuantity*/)"
cell.barcodeLabel.text = orderProducts.barcode //passedBarcode

You're attempting to retrieve property-values on the array of OrderProduct
rather than the instances inside it. It should probably
be:

cell.productcodeLabel.text = orderProducts[indexPath.row].productcode //passedProductcode
cell.detailLabel.text = orderProducts[indexPath.row].detail //passedDetail
cell.quantityLabel.text = "X (orderProducts.quantity/*passedQuantity*/)"
cell.barcodeLabel.text = orderProducts[indexPath.row].barcode //passedBarcode

But you need to make sure your array contains the proper models (obviously).

OK, as promised I'll try to make a more complete example. This probably won't match your requirements 100% (which are note entirely clear to me anyway) but hopefully It'll get you on the way...

In the viewController where you are actually passing the values I would suggest that you rather pass an array of model-objects. This could be something like this:

struct ProductModel {
    var productcode: String
    var detail: String
    var quantity: String
    var barcode: String
}

var models = [ProductModel]()

So you'll crete instances of ProductModel and append these to the array. When you're ready to move to the next viewController TestOrderViewController
by the looks of it you'll pass it the whole array (as it will have a matching property). This will either be done before you push the viewController, or in prepareForSegue based on how you handle the viewControllers.

Then in TestOrderViewController
you will have something like the below:

// UITableViewDataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return models.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("OrderCell", forIndexPath: indexPath) as! OrderTableViewCell
    let model = models[indexPath.row]
    cell.productcodeLabel.text = model.productcode
    cell.detailLabel.text = model.detail
    cell.quantityLabel.text = "X (model.quantity)"
    cell.barcodeLabel.text = model.barcode
    return cell
}

您可能感兴趣的

Integrate Segue with custom class Laravel Asgard CMS Menu with Custom Classes I'm using Asgard CMS in one of my prjects. I'm trying to print a menu...
UIWebView与UITableView的嵌套方案 简书的文章页主要由文章内容和评论列表两部分构成,考虑到评论列表的操作体验和复用性等其它问题,我们最终选择用UIWebView展示文章内容,而用原生的UITableView来展示评论。这就涉及到了UIWebView与UITableView嵌套的问题,难点在于怎样处理两个UIScrollView嵌套时滚...
UITableview displays only the first object of NSMu... I have a NSMutableArray and a grouped tableview that I populate from NSMutableArray. When I print NSmutableArray with NSLog Output is "String1","St...
UITableView 的优化技巧 UITableView 是 iOS 开发中的常用控件,用来加载列表数据,当列表数据量大或者列表布局过于复杂的时候有可能出现卡顿,影响用户体验,这个时候就要考虑对 UITableView 进行优化了。在这里将学习 VVebo 的 UITableView 优化技巧的心得记录下来。 缓存 Cell 高...
UITableView Cell内容不显示问题 最近新接手了一个比较坑的项目,逻辑近乎神逻辑。好不容易根据需求从一团乱线中抽离出来之后,一运行发现cell中的内容竟然只有第一个显示,于是硬着头皮再看cell中的代码,发现竟然又在self.contentView上添加了一层view来做视图展现(本人以前没这么干过) 然后就是新添加的这层...
Hello, buddy!

责编内容来自:Hello, buddy! (本文源链)
我还没有学会写个人说明!

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。