【发布时间】:2016-05-19 04:38:48
【问题描述】:
我正在处理一个由iOS 和swift 共同创建的项目。这个项目是一个基于套接字的应用程序。在这个应用程序中,数据存储在数据库中并从那里获取。当我想从表中获取数据时,我将获取数据到 NSManagedObject 类作为模型,当我想使用它们时,从他们的 NSManagedObject 模型中获取它们。我也应该说模型类是客观的c基础!现在,当我想在 swift 类中使用此模型数据并将它们转换为特定类时,会在运行时出错。请给我一个解决方案。这是我的代码:
-(NSMutableArray *)loadBills : (int) estateId : (int) personId {
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Bill" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSPredicate *pred = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"(personId = %d) AND (estateId = %d)",personId,estateId]];
[fetchRequest setPredicate:pred];
NSArray *fetchedObjects=[self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"billId" ascending:NO];
NSArray *sortedArray = [fetchedObjects sortedArrayUsingDescriptors:@[sort]];
NSMutableArray *array=[[NSMutableArray alloc]init];
for (NSManagedObject *info in sortedArray) {
Bill *bill=(Bill *)info;
[array addObject:bill];
}//for
return array;
}//loadBills
用于转换的 Swift 代码是:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! BillCell
let sa = getBillData().objectAtIndex(indexPath.row) as! Bill
print(sa.expDate)
return cell
}
getBillData() 函数是:
private func getBillData() -> NSMutableArray {
let dataLayer = DataLayer()
let person = dataLayer.getCurrentPerson()
let billArray = dataLayer.loadBills(person.estateId.intValue, person.personId.intValue)
return billArray
}
错误是:
无法将“NSManagedObject_Bill_”转换为 Bill。
【问题讨论】:
标签: ios objective-c swift core-data nsmanagedobject