錯誤描述
今天在Xcode 8下使用Core Data時,編譯時出現以下錯誤:
<unknown>:0: error: filename "Friend+CoreDataClass.swift" used twice: '/Users/.../Documents/Demo/Friend/Friend/Friend+CoreDataClass.swift' and '/Users/.../Library/Developer/Xcode/DerivedData/Friend-adfqrgytnrhhxnavbipcabnyztke/Build/Intermediates/Friend.build/Debug-iphonesimulator/Friend.build/DerivedSources/CoreDataGenerated/Friend/Friend+CoreDataClass.swift'
<unknown>:0: note: filenames are used to distinguish private declarations with the same name
<unknown>:0: error: filename "Friend+CoreDataProperties.swift" used twice: '/Users/.../Documents/Demo/Friend/Friend/Friend+CoreDataProperties.swift' and '/Users/.../Library/Developer/Xcode/DerivedData/Friend-adfqrgytnrhhxnavbipcabnyztke/Build/Intermediates/Friend.build/Debug-iphonesimulator/Friend.build/DerivedSources/CoreDataGenerated/Friend/Friend+CoreDataProperties.swift'
<unknown>:0: note: filenames are used to distinguish private declarations with the same name
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
仔細看下上面的報錯,發現是文件名沖突。Friend+CoreDataClass.swift 和 Friend+CoreDataProperties.swift 同時出現在兩個路徑下:
/Users/.../Documents/Demo/Friend/Friend/
/Users/.../Library/Developer/Xcode/DerivedData/Friend-adfqrgytnrhhxnavbipcabnyztke/Build/Intermediates/Friend.build/Debug-iphonesimulator/Friend.build/DerivedSources/CoreDataGenerated/Friend/
產生原因
Xcode 8中實體新添了一個Codegen選項,而其默認值是'Class Definition',表示自動為實體生成對應類文件(上面較長路徑下的文件)。
自動生成類文件.png
而我又用使用Editor->Create NSManagedObject Subclass手動為實體生成了類文件(上面較短路徑下的文件)。所以導致了文件重名。
解決方案
方案一:刪掉手動生成的類文件,直接使用自動生成的。
方案二:如果不想用系統自動生成的,我們可以將Codegen選項改為'Manual/None'。表示手動生成。
手動生成類文件.png
注意,使用方案二需要刪除已經自動生成的文件(上面較長路徑下的文件)。如果還是報錯,使用Product -> Clean清理下試試。