在Swift中使用Core Data时有关实现计算属性的任何建议吗?
使用生成的Managedobject类,我试图覆盖getter但是我收到错误:
‘NSManaged’ not allowed on computed properties
这意味着您无法覆盖瞬态(计算)属性的getter.
在下面的代码示例中,dateDue被定义为模型中的瞬态属性.
请注意,@ NSManaged行是由Xcode生成的 – 不是由我添加的.
@NSManaged var timeStamp: NSDate @NSManaged var dateDue: String { get { self.willAccessValueForKey("dateDue") var ddtmp = self.primitiveValueForKey("dateDue") as String? self.didAccessValueForKey("dateDue") if (ddtmp == nil) { let calendar = NSCalendar.currentCalendar() let components = calendar.components((NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit ),fromDate: self.timeStamp) ddtmp = "\(components.year * 1000 + components.month)" self.setPrimitiveValue(ddtmp,forKey: "dateDue") } return ddtmp! } }
首先,在数据模型中创建一个瞬态属性(section).因为它是瞬态的,所以它不是物理存储的,因此不存储在托管对象上下文中.
section属性如下所示:
该实体显示在此处:
类NSManagedobject子类应该具有计算’section’属性.此处显示了演示如何完成此操作的NSManagedobject子类:
class Number: NSManagedobject { @NSManaged var number: NSNumber var section: String? { return number.intValue >= 60 ? "Pass" : "Fail" } }
然后,必须将NSFetchedResultsController初始化程序中的sectionForKeyPath设置为数据模型中的瞬态属性键和缓存名称(如果需要).
override func viewDidLoad() { super.viewDidLoad() fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest(),managedobjectContext: managedobjectContext!,sectionNameKeyPath: "section",cacheName: "Root") fetchedResultsController?.delegate = self fetchedResultsController?.performFetch(nil) tableView.reloadData() } func fetchRequest() -> NSFetchRequest { var fetchRequest = NSFetchRequest(entityName: "Number") let sortDescriptor = NSSortDescriptor(key: "number",ascending: false) fetchRequest.predicate = nil fetchRequest.sortDescriptors = [sortDescriptor] fetchRequest.fetchBatchSize = 20 return fetchRequest }
结果是一个UITableViewController,其成绩按动态传递或失败排序: