Swift Core Data - 处理空获取结果

Swift Core Data - handling empty fetch result

我有一个简单的实体,一个 stationID 和一个类型,都是字符串

我用这个方法来搜索给定站号的类型,

 func returnStationType(stationTypeId: String) -> PersistantStationType {
        
        let context = container.viewContext
        
        let request = PersistantStationType.fetchRequest() as NSFetchRequest<PersistantStationType>
        request.predicate = NSPredicate(format: "%K == %@", #keyPath(PersistantStationType.stationId), stationTypeId as CVarArg)
        
        do {
            
            let result = try context.fetch(request)
            if result.count != 0 {
                
                let fetchedStationType = result.first!
                
                return fetchedStationType
                
            } else { print("4 Fetch result was empty for specified stationid: \(String(describing: stationTypeId))")
                
            }
            
        } catch { print("Fetch on goal id: \(String(describing: stationTypeId)) failed. \(error)") }
        
        
        return PersistantStationType.init()
    
    }

我这里调用方法:

let persistentStationType = persistenceController.returnStationType(stationTypeId: closestStation.id)
                
                let stationType = persistentStationType.type?.lowercased().capitalized
                
                let realName = helper.returnRealName(stationType: stationType ?? "None")
                
                let imageName = helper.returnStationTypeImage(stationType: stationType ?? "None")

如果未找到 stationId - 结果为空,我会在调用方法的代码(Bad Exec/Access)中崩溃 - 而不是在方法本身中。 (我对此并不感到惊讶,但我不确定如何处理它)

我无法使用 if let on 方法 .. 它不是可选的。我应该返回一个空对象并在获取结果为空时检查它吗?

感谢您的帮助。

我会将函数声明为 return 一个可选的,当没有找到时 return nil

func returnStationType(stationTypeId: String) -> PersistantStationType? {
    let context = container.viewContext

    let request: NSFetchRequest<PersistantStationType> = PersistantStationType.fetchRequest()
    request.predicate = NSPredicate(format: "%K == %@", #keyPath(PersistantStationType.stationId), stationTypeId)

    do {
        let result = try context.fetch(request)

        if result.count != 0 {
            return result[0]
        } else {
            print("4 Fetch result was empty for specified stationid: \(String(describing: stationTypeId))")
            return nil
        }
    } catch {
        print("Fetch on goal id: \(String(describing: stationTypeId)) failed. \(error)")
        return nil
    }
}

如果在错误方面,如果一个 id 存在多个对象(或 none),那么在这些情况下抛出错误会更好

func returnStationType(stationTypeId: String) throws -> PersistantStationType {
    let context = container.viewContext

    let request: NSFetchRequest<PersistantStationType> = PersistantStationType.fetchRequest()

    request.predicate = NSPredicate(format: "%K == %@", #keyPath(PersistantStationType.stationId), stationTypeId)

    do {
        let result = try context.fetch(request)

        switch result.count {
        case 0:
            throw FetchError("No station type found for id \(stationTypeId)")
        case 1:
            return result[0]
        default:
            throw FetchError("Multiple station types found for id \(stationTypeId)")
        }
    } catch let error as NSError {
        throw FetchError(error.localizedDescription)
    }
}

struct FetchError: LocalizedError {
    private let message: String

    var errorDescription: String? {
        message
    }

    init(_ message: String) {
        self.message = message
    }
}