我已将coredata的堆栈从新项目复制到现有项目,我从API获取数据并在应用程序启动时将其放入coredata但随机崩溃。 这是我的日志:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFSet addObject:]: attempt to insert nil'
*** First throw call stack:
(
0 CoreFoundation 0x000000010605a34b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x0000000105abb21e objc_exception_throw + 48
2 CoreFoundation 0x00000001060c3265 +[NSException raise:format:] + 197
3 CoreFoundation 0x0000000105ff262b -[__NSCFSet addObject:] + 155
4 CoreData 0x0000000101f025bb -[NSManagedObjectContext(_NSInternalChangeProcessing) _processPendingInsertions:withDeletions:withUpdates:] + 603
5 CoreData 0x0000000101efcc6c -[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:] + 2348
6 CoreData 0x0000000101f04449 -[NSManagedObjectContext(_NSInternalChangeProcessing) _prepareForPushChanges:] + 185
7 CoreData 0x0000000101f00ea2 -[NSManagedObjectContext save:] + 562
8 ETKA 0x00000001014f73a5 _TFC4ETKA11AppDelegate11saveContextfT_T_ + 149
9 ETKA 0x0000000101500d71 _TFC4ETKA11AppDelegate8saveJsonfT_T_ + 6113
10 ETKA 0x00000001014ff459 _TFFC4ETKA11AppDelegate10parseJSON1FT_T_U_FTGSqV10Foundation4Data_GSqCSo11URLResponse_GSqPs5Error___T_ + 31257
11 ETKA 0x0000000101422b8b _TTRXFo_oGSqV10Foundation4Data_oGSqCSo11URLResponse_oGSqPs5Error____XFdCb_dGSqCSo6NSData_dGSqS1__dGSqCSo7NSError___ + 203
12 CFNetwork 0x00000001088d26b0 __75-[__NSURLSessionLocal taskForClass:request:uploadFile:bodyData:completion:]_block_invoke + 19
13 CFNetwork 0x00000001088d1f5c __49-[__NSCFLocalSessionTask _task_onqueue_didFinish]_block_invoke + 308
14 Foundation 0x00000001055bf2cd __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 7
15 Foundation 0x00000001055befaf -[NSBlockOperation main] + 101
16 Foundation 0x00000001055bd6ac -[__NSOperationInternal _start:] + 672
17 Foundation 0x00000001055b95ef __NSOQSchedule_f + 201
18 libdispatch.dylib 0x0000000106f350cd _dispatch_client_callout + 8
19 libdispatch.dylib 0x0000000106f12e6b _dispatch_queue_serial_drain + 236
20 libdispatch.dylib 0x0000000106f13b9f _dispatch_queue_invoke + 1073
21 libdispatch.dylib 0x0000000106f163b7 _dispatch_root_queue_drain + 720
22 libdispatch.dylib 0x0000000106f1608b _dispatch_worker_thread3 + 123
23 libsystem_pthread.dylib 0x00000001072e4746 _pthread_wqthread + 1299
24 libsystem_pthread.dylib 0x00000001072e4221 start_wqthread + 13
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
这是我在appDelegate中的代码:
import UIKit
import GoogleMaps
import CoreData
@available(iOS 10.0, *)
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var nrows = 0
var namesArray = [String]()
var codeArray = [String]()
var rankingArray = [String]()
var mornStart = [String]()
var mornEnd = [String]()
var eveStart = [String]()
var eveEnd = [String]()
var addressArray = [String]()
var telArray = [String]()
var latArray = [String]()
var lngArray = [String]()
var cityArray = [String]()
var iDArray = [String]()
var locss = [Locs]()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
parseJSON1()
GMSServices.provideAPIKey("AIzaSyDsDqj0EMYZ-C4lGF3tmbntZtzurLl6_J4")
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Core Data stack
@available(iOS 10.0, *)
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Model")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
func parseJSON1(){
let requestURL: NSURL = NSURL(string: "xxxxxxx")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest as URLRequest) {
(data, response, error) -> Void in
let readableJSON = JSON(data: data! , options: JSONSerialization.ReadingOptions.mutableContainers, error: nil)
var Name = readableJSON[0]["Name"].stringValue as String!
print(Name)
self.nrows = readableJSON.count
for i in 0...self.nrows{
if let Name = readableJSON[i]["Name"].string as String! {
var ID = readableJSON[i]["Id"].intValue
var iDString = String (ID)
self.namesArray.append(Name)
var code1 = readableJSON[i]["Code"].string as String!
if code1 == nil {
code1 = " "
}
var desc = readableJSON[i]["Address"].string as String!
if desc == nil {
desc = " "
}
var rank = readableJSON[i]["Ranking"].string as String!
if rank == nil {
rank = " "
}
var cit = readableJSON[i]["Province"].string as String!
if cit == nil {
cit = " "
}
var moS = readableJSON[i]["Morning_Start"].string as String!
if moS == nil {
moS = " "
}
var moF = readableJSON[i]["Morning_Finish"].string as String!
if moF == nil {
moF = " "
}
var evS = readableJSON[i]["Evening_Start"].string as String!
if evS == nil {
evS = " "
}
var evF = readableJSON[i]["Evening_Finish"].string as String!
if evF == nil {
evF = " "
}
var tel = readableJSON[i]["Telephone"].string as String!
if tel == nil {
tel = " "
}
var lat = readableJSON[i]["Lat"].double
let latString = String (describing: lat)
var lng = readableJSON[i]["Lng"].double
var lngString = String (describing: lng)
var newLoc = Locs(iD: iDString, state: cit!, name: Name, type: rank!, code: code1!, wHoursMorning: moS! + moF!, wHoursEvening: evS! + evF!, address: desc!, phone: tel!, lat: latString, lng: lngString)
self.locss.append(newLoc)
print(Name)
}
// self.idArray.append(iDString)
// print(Name)
print (self.nrows)
}
/* for j in 0...self.nrows {
print(self.namesArray[j])
}*/
self.saveJson()
}
task.resume()
saveJson()
}
func saveJson() {
/* let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let task = Task(context: context)
task.name = textField.text
task.isImportant = isImp.isOn
//save the data into coredata
(UIApplication.shared.delegate as! AppDelegate).saveContext()*/
for i in 0 ..< self.locss.count{
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let store = Store(context: context)
store.name = self.locss[i].name
store.address = self.locss[i].address
store.city = self.locss[i].state
store.code = self.locss[i].code
store.morningStart = self.locss[i].wHoursMorning
store.eveningStart = self.locss[i].wHoursEvening
store.telephone = self.locss[i].phone
store.lat = self.locss[i].lat
store.lng = self.locss[i].lng
store.ranking = self.locss[i].type
store.iD = self.locss[i].iD
(UIApplication.shared.delegate as! AppDelegate).saveContext()
print("savedddd")
}
}
}