Error: Could not find overload for 'title'

2019-06-14 06:03发布

问题:

Currently I have a subclass of NSManaged object called Folder with property called item that is of type NSSet. I have a function to return a NSMutableArray and I am trying to display the data in a tableview (and then rearrange the order displayed in the table).

class Folder: NSManagedObject {

@NSManaged var title: String
@NSManaged var date: NSDate
@NSManaged var item: NSSet

func itemMutableArray() -> NSMutableArray {
    return NSMutableArray(array: (item.allObjects as! [Checklist]).sorted{ $0.date.compare($1.date) == NSComparisonResult.OrderedAscending } )
}

TableViewController:

 var itemMutableArray: NSMutableArray!
 itemMutableArray = folder.itemMutableArray() 

 cell.textLabel?.text = itemMutableArray[indexPath.row].title //Error

Unfortunately this returns an error in my tableview when using this function.

Error could not find overload for 'title' that accepts the supplied arguments

Ultimately what I am trying to achieve is to display the data and move the cells around to change the order of the NSSet.

 table.didMoveCellFromIndexPathToIndexPathBlock = {(fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) -> Void in

  let delegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
  let context: NSManagedObjectContext = delegate.managedObjectContext!

  context.deleteObject(self.itemArray[indexPath!.row] as NSManagedObject )  

  self.itemArray.exchangeObjectAtIndex(toIndexPath.row, withObjectAtIndex: fromIndexPath.row)

 }

PS: Originally I had a function to return an array of the object but I was unable to modify the order of the NSSet as they are not ordered.

func itemArray() -> [Item] {
    let sortDescriptor = NSSortDescriptor(key: "date", ascending: true)
    return item.sortedArrayUsingDescriptors([sortDescriptor]) as! [Item]
}

Does anybody have any suggestions with where I am currently going wrong ?

回答1:

The problem with the expression itemMutableArray[indexPath.row].title is that, because you have typed itemMutableArray as an NSMutableArray, itemMutableArray[indexPath.row] is an AnyObject. Thus, Swift has no reason to believe that this thing has a title property. You need to cast it to something that does have a title property (though it would be much better to avoid the use of NSMutableArray completely, if possible, since a Swift array is mutable).