简体   繁体   中英

Swift 3 Core Data fetch issue

The function below is used to get data for tableview

func fetchProfiles() -> Array<User> {
    var users: Array<User> = []
    let fetchRequest: NSFetchRequest<Profile> = Profile.fetchRequest()
    let fetchedData = try! context.fetch(fetchRequest)
    if (!fetchedData.isEmpty) {
        print(fetchedData)
        for i in 0...fetchedData.count {
            var user: User = User()
            user.userName = fetchedData[i].profileName
            user.userSurname = fetchedData[i].profileSurname
            user.userPhoto = fetchedData[i].profilePhoto
            users.append(user)
        }
        return users
    }
    else {
        return users
    }
}

"User" is a simple struct. "Profile" is an entity in Core Data. I create an array of structs to use them for cells in table. Code has no errors(for xCode). When there is no fetched data, it skips appending array, but when there is some info, app crashes with error:

fatal error: NSArray element failed to match the Swift Array Element type

For unknown reason, there were problems with auto generated headers of Core Data entities. I just deleted all files from folder:

/Users/user/Library/Developer/Xcode/DerivedData/MyApp/Build/Intermediates/MyApp.build/Debug-iphonesimulator/MyApp.build/DerivedSources/CoreDataGenerated

then cleaned my project with

command+shift+k

checked my core data model for some possible issues and rebuilt the whole project. Magic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM