5

I'm trying to use a func I extended UIViewController with. I added self to the different func's arguments but the func not gives me "Implicit use of 'self' in closure; use 'self.' to make capture semantics explicit" error. Tried even to apply a weak self reference. The func seems to be never running anyway

te array is declared

var managedComicsArray = [NSManagedObject]()

in viewDidLoad :

guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {return}
    managedContext = appDelegate.persistentContainer.viewContext

the button

@IBAction func addComicButtonTapped(_ sender: UIBarButtonItem) {

    print("add button tapped")

    weak var weakSelf = self // ADD THIS LINE AS WELL


    let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)

    alert.addTextField { (textField) in
        textField.placeholder = "Some default text"
        textField.keyboardType = .numberPad
    }

    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
//            let textField = alert.textFields![0] // Force unwrapping because we know it exists.
        let textField = alert!.textFields![0]
        print("Text from textField: \(textField.text)")


        guard let grabbedNumber = Int16(textField.description) else {return}
//the func below gives the error
        weakSelf?.addRecordIfnotPresent(newIssueNumber: grabbedNumber, theManagedContext: self.managedContext, theEntityName: self.kComicEntityName, managedArray: &self.managedComicsArray)


        self.myTableView.reloadData()
    }))

    alert.addAction(UIAlertAction(title: "cancel", style: .cancel, handler: nil))

    // 4. Present the alert.
    self.present(alert, animated: true, completion: nil)


   //end of button
}

the extended method:

func addRecordIfnotPresent(newIssueNumber: Int16, theManagedContext: NSManagedObjectContext, theEntityName: String, managedArray: inout [NSManagedObject]) {

    print("adding func started")

    let comicFetch: NSFetchRequest<Comic> = Comic.fetchRequest()
    var isPresent = true

    do {
        managedArray = try theManagedContext.fetch(comicFetch)


        if !managedArray.isEmpty {

        //*****************************************************************
        for comic in managedArray {

            var comicToCheck = Comic()
            comicToCheck = comic as! Comic

            if comicToCheck.wholeSeriesNumber == newIssueNumber {
                print("number \(newIssueNumber) is alredy present")
                return
            } else {
                isPresent = false
                print("number not present, keep on!")
            }

        }


        guard isPresent == false else {return}
        saveSingleComicWithNumber(withIssueNumber: Int(newIssueNumber), theEntityName: theEntityName, theManagedContext: theManagedContext)
        print("created Comic!")
        try theManagedContext.save()
        print("saved context!")
        //*****************************************************************

        } else {
            saveSingleComicWithNumber(withIssueNumber: Int(newIssueNumber), theEntityName: theEntityName, theManagedContext: theManagedContext)

        }










    } catch let error as NSError {
        print("Fetch error: \(error) description: \(error.userInfo)")
    }


}






func saveSingleComicWithNumber(withIssueNumber: Int, theEntityName: String, theManagedContext: NSManagedObjectContext) {
    let entity = NSEntityDescription.entity(forEntityName: theEntityName, in: theManagedContext)!

    let comicToAdd = Comic(entity: entity, insertInto: theManagedContext)


    comicToAdd.wholeSeriesNumber = Int16(withIssueNumber)
    comicToAdd.issueInCollection = false
    comicToAdd.titleOfItalianSerie = "title"

    if comicToAdd.wholeSeriesNumber == 2 {
        comicToAdd.issueInCollection = false
    }


    do {
        try theManagedContext.save()
    } catch let error as NSError {
        print("could not save. \(error), \(error.userInfo)")
    }
}
biggreentree
  • 1,633
  • 3
  • 20
  • 35
  • 2
    Note there is no need for `weak self` in your method. You can capture strongly. The controller cannot be deallocated when the alert is still visible. – Sulthan Apr 04 '17 at 09:39
  • fine! I applied 'self.addRecordIfnotPresent' is that you mean? but something must be wrong with the grabbing/converting from the alert, the func never evalues – biggreentree Apr 04 '17 at 09:45
  • I cannot replicate your problem at all. Your original code compiles fine for me. If the function does not evaluate it probably means `Int16(textField.description)` fails and your `guard` returns. – Sulthan Apr 04 '17 at 09:47
  • @biggreentree same here i don't have any problem in compiling your code. Can you post what you doing in your `addRecordIfnotPresent` function – vinothp Apr 04 '17 at 09:49
  • thanks for your help, added the function – biggreentree Apr 04 '17 at 09:51
  • @biggreentree How is `self.managedComicsArray` declared? Why do you use an `inout` param instead of returning it as a normal return value? – Sulthan Apr 04 '17 at 09:54
  • when I moved the func in a separate swift file as an extension it was required to change it so in order the func to be working, so the func is used directly as any VC method – biggreentree Apr 04 '17 at 09:59
  • sorry, read wrong your question! is declare this way var managedComicsArray = [NSManagedObject]() – biggreentree Apr 04 '17 at 10:07
  • The function cannot run because your `Int16(textField.description)` line will never let it continue. You cannot use `textField.description`. You have to use `textField.text`, e.g. `Int16(textField.text ?? "")`. – Sulthan Apr 04 '17 at 10:10

0 Answers0