Realm结果中的属性为nil

时间:2019-05-20 06:49:30

标签: swift realm

我不明白为什么我无法打印出领域结果的属性。当我打印现存的Cart [i]。$ {property}时,它总是为我的所有迭代i提供默认值。

语句print(existingCart)没问题。它在属性中包含非默认值。它返回:

    Results<Product> <0x7fe5d8f3a770> (
    [0] Product {
        itemImage = <ffd8ffe0 00104a46 49460001 01000048 00480000 ffe10058 — 232200 total bytes>;
        itemName = Ground Beef;
        price = 6.53;
        unit = 450 g;
        quantity = 1;
        isInCart = 0;
    },
    [1] Product {
        itemImage = <ffd8ffe0 00104a46 49460001 01000048 00480000 ffe1004c — 153015 total bytes>;
        itemName = Chicken Drumsticks;
        price = 9.06;
        unit = 1.25 kg;
        quantity = 1;
        isInCart = 0;
    },
    [2] Product {
        itemImage = <ffd8ffe0 00104a46 49460001 01000048 00480000 ffe10058 — 242980 total bytes>;
        itemName = Ground Turkey;
        price = 6.91;
        unit = 450 g;
        quantity = 2;
        isInCart = 0;
    },
    [3] Product {
        itemImage = <ffd8ffe0 00104a46 49460001 01000048 00480000 ffe10058 — 224128 total bytes>;
        itemName = Canned Beans;
        price = 1.79;
        unit = 398 mL;
        quantity = 1;
        isInCart = 0;
    },
    [4] Product {
        itemImage = <ffd8ffe0 00104a46 49460001 01000048 00480000 ffe10058 — 252231 total bytes>;
        itemName = Frosted Flakes;
        price = 9.49;
        unit = 1.06 kg;
        quantity = 1;
        isInCart = 0;
    },
    [5] Product {
        itemImage = <ffd8ffe0 00104a46 49460001 01000048 00480000 ffe1004c — 165948 total bytes>;
        itemName = Gouda Cheese;
        price = 4.99;
        unit = 300 g;
        quantity = 1;
        isInCart = 0;
    }
)

这是我尝试从Realm加载数据的方式:

private func loadExistingCart() {
    let realm = try! Realm()

    let existingCart = realm.objects(Product.self)
    print(existingCart) // see above
    for i in 0..<existingCart.count {
        print(existingCart[i].itemName) // empty string
        print(existingCart[i].price) // 0.0
        print(existingCart[i].quantity) // 0
        print(existingCart[i].unit) // empty string
        cart.addItem(existingCart[i]) // adds
    }
}

这是产品类别:

import UIKit
import Foundation
import Realm
import RealmSwift

class Product : Object {

    // MARK: Properties
    @objc var itemImage = Data()
    @objc var itemName: String = ""
    @objc var price: Float = 0.0
    @objc var unit: String = ""
    @objc var quantity: Int = 0
    @objc var isInCart: Bool = false

    convenience init?(itemImage: UIImage?, itemName: String, price: Float, unit: String, quantity: Int, isInCart: Bool = false) {
        self.init()
        // itemName, unit, category should not be empty
        guard (!itemName.isEmpty && !unit.isEmpty) else {
            return nil
        }

        // price should not be a negative number
        guard (price >= 0) else {
            return nil
        }

        // Initialize stored properties
        self.itemImage = UIImageJPEGRepresentation(itemImage!, 0.9)!
        self.itemName = itemName
        self.price = price
        self.unit = unit
        self.quantity = quantity
        self.isInCart = isInCart
    }

    override class func primaryKey() -> String? {
        return "itemName"
    }

}

这是保存产品的方式

private func saveToCart(product: Product, update: Bool) {
    let realm = try! Realm()
    print(product)
    try! realm.write {
        realm.add(product, update: true)
    }
}

2 个答案:

答案 0 :(得分:2)

您在其中的Product类的声明中犯了一个小错误,这是使用Realm的常见陷阱。

如果您回顾其文档中的所有Realm示例,您会发现每个成员字段都应声明为如下所示:

views.py

是的,您错过了每个属性上的class FileUploadView(View): form_class = DocumentForm success_url = reverse_lazy('home') template_name = 'file_upload.html' def get(self, request, *args, **kwargs): upload_form = self.form_class() return render(request, self.template_name, {'upload_form': upload_form}) def post(self, request, *args, **kwargs): upload_form = self.form_class(request.POST, request.FILES) if upload_form.is_valid(): form_done = upload_form.save(commit=False) # save the form but don't commit form_done.user = self.request.user # request the user form_done.save() # finish saving the form return redirect(self.success_url) else: return render(request, self.template_name, {'upload_form': upload_form}) 修饰符。返回并添加到每个属性中,它应该就可以开始工作了。为了完整起见,这应该是属性声明:_

@objc dynamic var itemImage = Data()

您可以在Google的dynamic关键字上进行解释。它基于以下事实:您拥有的对象只是数据库对象的代理,并且Realm需要拦截属性访问才能实际查询数据库并检索该属性的值。如果您尝试在调试器中查看对象,则会看到与问题相同的效果-它只包含默认值。

答案 1 :(得分:0)

我对Realm的工作方式还不太熟悉,无法说出为什么您似乎无法按索引访问对象,但是也许您可以尝试将它们作为Sequence的一部分来访问?

let existingCart = realm.objects(Product.self)

for item in existingCart {
    print(item.itemName)
    print(item.price)
    print(item.quantity)
    print(item.unit)
}