iOS - 在同一个项目中使用Swift和Objective c?

时间:2016-05-19 04:38:49

标签: ios objective-c swift core-data nsmanagedobject

我正在处理由iOSswift共同创建的项目。这个项目是一个套接字基础应用程序在这个应用程序中,数据存储在数据库中并从那里获取。当我想从表中获取数据时,我将数据作为模型提取到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。

1 个答案:

答案 0 :(得分:-1)

首先,在cellForItemAtIndexPath函数中从数据库加载数据并不安全,也不是一个好习惯,因为每次滚动集合视图时此函数都会调用,而是将Bill对象加载到数组中并设置为数据源并填充该数据源中的单元格。这可能是你获得nil对象的另一个原因。

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! BillCell
    let sa = getBillData().objectAtIndex(indexPath.row)
    print(sa.valueForKey("expDate")!.description)
    return cell
}