Ant*_*ito 7 core-data one-to-many ios swift
我一直在使用Swift在Core Data中使用to-many关系时遇到一些困难.
我的数据模型

我想要做的是使用a的实例,Country然后显示Contacts该国家的所有公民.正如我一直在尝试这样做,我构建了一个UITableViewController,它将显示该国家的所有公民.但是我遇到了实际Contacts脱离关系的重大问题citizensOfCountry.这是我正在使用的代码(仅相关部分).
class ShowingCitizensOfCountry: UITableViewController {
var countryToShow: Country?
//This is a value that is passed by a prepareForSegue method
override func viewDidLoad() {
//how do I get a list/set/other iterable object of Contacts?
//***Line in question***
let listOfPeople = countryToShow!.citizensOfCountry
for citizen in listOfPeople {
println(citizen)//THIS IS NOT WORKING
}
}
Run Code Online (Sandbox Code Playgroud)
所以,这根本不起作用.现在在for循环中我得到一个编译错误Type 'Contacts' does not conform to protocol 'Sequence Type'.我不明白的是它只是类型联系...我会认为这将是某种集合.所以,那不行,所以我尝试了这个.
let listOfPeople = countryToShow!.citizensOfCountry as! [Contacts]
Run Code Online (Sandbox Code Playgroud)
这也不起作用,我得到错误'NSArray' is not a subtype of 'Contacts'.接下来我尝试使用NSSet进行转换.
let listOfPeople = countryToShow!.citizensOfCountry as! NSSet<Contacts>
Run Code Online (Sandbox Code Playgroud)
不幸的是,这也不起作用,我得到了警告Cast from 'Contacts' to unrelated type 'NSSet' always fails和Cannot specialize non-generic type 'NSSet'.接下来我尝试了别的东西.我尝试过使用这种valueForKey方法.
let listOfPeople = countryToShow!.citizensOfCountry.valueForKey("name") as! Set<String>
Run Code Online (Sandbox Code Playgroud)
这有效!我只能打印出该国公民的所有人的名字.但是我不明白为什么.我使用时为什么会起作用,valueForKey("name")但我无法获得个人联系?有没有更好的方法来做到这一点,我错过了?关于为什么我无法Contacts从单曲中收集任何内容的任何解释Country都非常感谢.谢谢.
对不起,因为我真的很累,我看不懂一切.但是从我读过的内容来看,你想要得到一个应该是NSSet的国家的公民.要做到这一点你可以简单地做:
let contacts = yourArrayOfCountries.flatMap {
$0.citizensOfCountry.allObjects as! [Contacts]
}
Run Code Online (Sandbox Code Playgroud)
根据你的评论:
let contacts = countryToShow!.citizensOfCountry.allObjects as! [Contacts]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5742 次 |
| 最近记录: |