【发布时间】:2020-10-24 16:36:13
【问题描述】:
在之前的一个问题中,我询问了如何将类的实例存储在本地数据库中,有人建议我使用领域作为存储方法。我已经设置了我的领域并完成了研究,但是,在我的课堂上,我有一个对象数组,当我尝试将对象数组设置为“@objc 动态”以便将其存储到领域文件中时,它不允许这样做,抛出错误“属性不能被标记@objc,因为它的类型不能在Objective-C中表示”。我真的不明白这是什么意思,或者在 Objective-C 中可以表示什么”。
//
// MealPlan.swift
// IA
//
// Created by Ian Dong on 8/25/20.
// Copyright © 2020 Ian Dong. All rights reserved.
//
import Foundation
import RealmSwift
class MealPlan: Object {
@objc dynamic var ingerdientList: [IngerdientCost] = [];
var k: Int = 0;
var serving : Int
@objc dynamic var cost : [IngerdientCost] = [];
var name : String;
init ( size: Int, name: String){
self.serving = size;
self.name = name;
}
func addIngerdient (newIngerdient: IngerdientCost){
ingerdientList.insert(newIngerdient, at: k);
k = k+1;
}
func removeINgerdient(theIngerdient: IngerdientCost)
{
var c: Int = 0;
while theIngerdient.amount != ingerdientList[c].amount && c <= k
{
c=c+1;
}
ingerdientList.remove(at: c);
k=k-1;
}
func getCost() -> Array<IngerdientCost>
{
var c: Int = 0;
while c <= ingerdientList.count
{
cost[c].ingerdientName = ingerdientList[c].ingerdientName;
cost[c].amount = ingerdientList[c].amount * Double(serving);
c = c+1;
}
return cost;
}
func setServing( serv: Int)
{
self.serving = serv;
}
}
//
// Ingerdient cost .swift
// IA
//
// Created by Ian Dong on 8/25/20.
// Copyright © 2020 Ian Dong. All rights reserved.
//
import Foundation
import RealmSwift
class IngerdientCost: Object{
init(Name: Ingerdient, Amount: Double )
{
self.amount = Amount;
self.ingerdientName = Name;
}
var ingerdientName: Ingerdient;
var amount: Double;
}
【问题讨论】:
-
IngerdientCost还必须符合Object -
另外,你应该使用
List而不是数组:var ingerdientList: List<IngerdientCost>() -
如何让 IngerdientCost 符合 Object?
-
列表和数组有什么区别?
-
您的领域对象丢失
self.init()。请参阅Models - 对象子类的自定义初始化程序部分。此外,这对于领域列表对象@objc dynamic var ingerdientList: [IngerdientCost] = [];是不正确的。需要是let ingredientList = List<IngredientCost>()。花几分钟时间阅读 Realm 中的列表Getting Started Guide
标签: objective-c swift database realm