CoreData , executeFetchRequest, Extra Argument "Error" in Call [duplicate] - ios

This question already has answers here:
Swift 2 ( executeFetchRequest ) : error handling
(5 answers)
Closed 7 years ago.
https://www.dropbox.com/s/vyzdrjlpvdcuill/managedContext.png?dl=0
I had this working January and when I ran it today, I was presented with this error.
I have tried to understand the new method of error handling, sadly I am not grasping it.
first time poster.
Sincerely,
rob

You have extra argument, which is the error,
Simple remove it.
Also this is a working code:
let fetchRequest = NSFetchRequest(entityName: "movieQuoteEntityName")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "lastTouchDate", ascending: false)]
var error :NSError? = nil
let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
var context: NSManagedObjectContext? = nil
let movieQuotes = context!.executeFetchRequest(fetchRequest)

Well, with the Swift 2.0, they changed the whole error handling stuff so you are not able to declare that way.
Swift has try-catch now for the error handling, so you may change all of the old error handling methods.

Related

Xcode; How to call function in AppDelegate from another ViewController [duplicate]

This question already has answers here:
How do I get a reference to the AppDelegate in Swift?
(18 answers)
Closed 4 years ago.
I'm using Swift and the newest Xcode version.
I have this code in AppDelegate.swift:
func testPrint(string: String) {
print(string)
}
I can successfully call the function from the file ViewController.swift like this:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.testPrint(string: "Hello!")
But if I'm trying to call the function from TodayViewController.swift, which is for Apples Today Extension, I'm getting the following error:
Use of undeclared type 'AppDelegate'
Why that?
Try something along those lines:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.testPrint(string: "Hello!")
EDIT:
'Today Extension' and App live in a different contexts so it is not possible.

Update Date Sorting Alternative

I am currently trying to update the code for a Udemy course I purchased a couple of months ago, which was fully working in the Swift 2.2 version. However, I am having issues with this particular function, which really just sorts and displays recent chats (with preview).
Here is the code:
func loadRecents() {
firebase.child("Recent").queryOrderedByChild("userId").queryEqualToValue(backendless.userService.currentUser.objectId).observeEventType(.Value, withBlock: {
snapshot in
self.recents.removeAll()
if snapshot.exists() {
let sorted = (snapshot.value!.allValues as NSArray).sortedArrayUsingDescriptors([NSSortDescriptor(key: "date", ascending: false)])
for recent in sorted {
self.recents.append(recent as! NSDictionary)
firebase.child("Recent").queryOrderedByChild("chatRoomID").queryEqualToValue(recent["chatRoomID"]).observeEventType(.Value, withBlock: {
snapshot in
})
}
}
self.tableView.reloadData()
})
}
I get the error here:
let sorted = (snapshot.value!.allValues as NSArray).sortedArrayUsingDescriptors([NSSortDescriptor(key: "date", ascending: false)])
I beleive the sortedArrayUsingDescriptors is deprecated, but I am still not sure. What could be a replacement of this current code?
Thanks in advance!
Update:
This is the error I am getting:
THread 1: EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP, subcode=0x0)
The specific answer to the question: what is a replacement (in Swift 3):
let sorted = ((snapshot!.value! as AnyObject).allValues as NSArray)
.sortedArray(using: [NSSortDescriptor(key: "date", ascending: false)])
Also, the code posted basically works - although the code inside the for recent in sorted section is malformed for Swift 3.
recent["chatRoomID"] in that section may be an issue as the data within sorted may not be strings - they may be dictionaries. It depends on your Firebase structure.
Lastly, it's probably a good idea to reduce you're dependency on NSSortDescriptors etc and do it in a more Swifty way.
See my answer to your prior question
Swift 3 Firebase update code convertion - sorting

Saving to CoreData while looping through a array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I get the this string "85:ABC ,83:CFD" after downloading from a web service.I need to store these values to CoreData table TABLE_JOBTITLE. I have the below code
var designationDictionaryArray = results.componentsSeparatedByString(",")
var index: Int = 1
for item in designationDictionaryArray
{
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity = NSEntityDescription.entityForName("TABLE_JOBTITLE",
inManagedObjectContext:managedContext)
let job = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext: managedContext)
job.setValue(String(index), forKey: "column_Id")
job.setValue(String(item.componentsSeparatedByString(":")[0]), forKey: "column_Server_Id")
job.setValue(String(item.componentsSeparatedByString(":")[1]), forKey: "column_Job_Name")
print("Column_Id")
print(index)
print("Column_Server_Id")
print(String(item.componentsSeparatedByString(":")[0]))
print("column_Job_Name")
print(String(item.componentsSeparatedByString(":")[1]))
do {
try managedContext.save()
print("saved job title")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
self.desiginationArray.append(item.componentsSeparatedByString(":")[1])
index = index + 1
}
I am able to iterate through each data but the when i store it in the table..It get stored like below
coulmn_Id column_ServerId column_Job_Title
1 83 CFD
1 83 CFD
Could anyone help me with corrected code or reason for this bizarre behavior please..
I suspect one of two things:
The value in result is not as you expect.
The manner in which you are checking the output is faulty.
I lean towards the latter as I do not see any way both entities could be assigned the same column ID in a single run through.
Put breakpoints up top to check the value of results and the array returned from results.componentsSeparatedByString(",").
Show the code you used to iterate through the table to check it. My bet is that you are not showing the true output. What is the output from the print lines within the loop? If it looks something like this:
Column_Id
1
Column_Server_Id
85
column_Job_Name
ABC
Column_ID
2
Column_Server_ID
83
Column_ID
CFD
Then I'd say, for sure, you are not properly reading back your results from Core Data. Let us see where you are getting that final table.
I don't know what the problem was the same code worked as it should.

"CoreData: error: NULL _cd_rawData but the object is not being turned into a fault"

This is a part if code when error happens:
class func randomWord() -> TBWord {
let randomIndex = Int(arc4random_uniform(UInt32(TBAppSettings.wordsForCurrentGame.count)))
let word = TBAppSettings.wordsForCurrentGame[randomIndex]
TBAppSettings.wordsForCurrentGame.removeAtIndex(randomIndex)
MagicalRecord.saveWithBlock { context in
let word = TBWord.findWordWithIdentifier(word.identifier, inContext: context) //here error happens
word?.used = true
}
return word
}
How can I workaround this? I know about other questions about this problem, but they are not enough for me.
(Besides the fact that MagicalRecord is a big misunderstanding of how to use Core Data properly...)
Have you tried to run you code with -com.apple.CoreData.ConcurrencyDebug 1 as a launch argument? This smells like a threading problem.

exc-bad-instruction code=i386_invop

I'm getting this error in latest version of xcode using swift 2
on line
let s = linkTxt.text
Text in linkTxt appears by button "pasteFromClipBoard"
let s = linkTxt.text
let u = NSURL(string: s!)
let file = u?.lastPathComponent
What is the reason of it and how to fix it?
Update:
the problem appears in function saveData() which calls when file downloading is finished. It calls from NSURLSessionDataTask function. More interesting, that in start-downloading-button there are the same lines where filename is generating and there is no such error on it. I fixed these issues by declaring variables, writing text's values into them and use these variables in saveData() except textObject.text; I had to delete lines with NSUserDefaults from saveData() too because I got the same error. Did understand nothing >_<
Update 2:
It's really a bug. I've deleted this line and wrote again - problem fixed
linkTxt.txt is returning nil and NSURL(string: s!) will try to forcefully unwrap it.
let s = linkTxt.text
if let s = linkTxt.txt {
let u = NSURL(string: s!)
let file = u?.lastPathComponent
}

Resources