1
votes

ERROR :

2016-07-27 13:53:24.004 DataManipulationApp[1379:56100] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]'
*** First throw call stack:
(
0   CoreFoundation                      0x000000010ecc5d85 __exceptionPreprocess + 165
1   libobjc.A.dylib                     0x000000010f16cdeb objc_exception_throw + 48
2   CoreFoundation                      0x000000010eba3804 -[__NSArrayM objectAtIndex:] + 212
3   DataManipulationApp                 0x000000010d06f36d _TFC19DataManipulationApp14ViewController16btn_Edit_ClickedfCSo8UIButtonT_ + 861
4   DataManipulationApp                 0x000000010d06f9ea _TToFC19DataManipulationApp14ViewController16btn_Edit_ClickedfCSo8UIButtonT_ + 58
5   UIKit                               0x000000010d603a8d -[UIApplication sendAction:to:from:forEvent:] + 92
6   UIKit                               0x000000010d776e67 -[UIControl sendAction:to:forEvent:] + 67
7   UIKit                               0x000000010d777143 -[UIControl _sendActionsForEvents:withEvent:] + 327
8   UIKit                               0x000000010d776263 -[UIControl touchesEnded:withEvent:] + 601
9   UIKit                               0x000000010d67699f -[UIWindow _sendTouchesForEvent:] + 835
10  UIKit                               0x000000010d6776d4 -[UIWindow sendEvent:] + 865
11  UIKit                               0x000000010d622dc6 -[UIApplication sendEvent:] + 263
12  UIKit                               0x000000010d5fc553 _UIApplicationHandleEventQueue + 6660
13  CoreFoundation                      0x000000010ebeb301 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
14  CoreFoundation                      0x000000010ebe122c __CFRunLoopDoSources0 + 556
15  CoreFoundation                      0x000000010ebe06e3 __CFRunLoopRun + 867
16  CoreFoundation                      0x000000010ebe00f8 CFRunLoopRunSpecific + 488
17  GraphicsServices                    0x000000011191bad2 GSEventRunModal + 161
18  UIKit                               0x000000010d601f09 UIApplicationMain + 171
19  DataManipulationApp                 0x000000010d0743e2 main + 114
20  libdyld.dylib                       0x000000010fc3792d start + 1
21  ???                                 0x0000000000000001 0x0 + 1
 )
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

Code:

GETTING MENTIONED ERROR FOR THE POSTED CODES, I NEED KIND HELP TO SOLVE IT

import UIKit

class HomeCellView: UITableViewCell
{
    @IBOutlet weak var btnDelete: UIButton!
    @IBOutlet weak var btnEdit: UIButton!
    @IBOutlet weak var lbl_Email: UILabel!
}

class ViewController: UIViewController, UITableViewDataSource,    UITableViewDelegate
{
    @IBOutlet weak var HomeTableView: UITableView!
    var databasepath:String!
    var arrayStudInfo:NSMutableArray!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        arrayStudInfo = NSMutableArray()

        let filemgr = NSFileManager.defaultManager()
        let dirpath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let docdir = dirpath[0] as String
        databasepath = docdir.stringByAppendingString("StudentDataManipulation.sqlite");

        if filemgr.fileExistsAtPath(databasepath as String)
        {
            let contactDB = FMDatabase(path: databasepath as String)

            if contactDB == nil
            {
                print("Error: \(contactDB.lastErrorMessage())")
            }

            if contactDB.open()
            {
                let sql_stmt = "CREATE TABLE IF NOT EXISTS StudentData (Name TEXT, Phone TEXT, Email TEXT PRIMARY KEY  NOT NULL, Comment TEXT)"

                if !contactDB.executeStatements(sql_stmt)
                {
                    print("Error: \(contactDB.lastErrorMessage())")
                }

                contactDB.close()
            }
            else
            {
                print("Error: \(contactDB.lastErrorMessage())")
            }
        }
    }

    override func viewWillAppear(animated: Bool)
    {
        super.viewWillAppear(true)
        listAllData()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    // UITableViewDataSource Methods
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return arrayStudInfo.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {

        let cell = tableView.dequeueReusableCellWithIdentifier("cellhome") as! HomeCellView

        cell.lbl_Email.text = arrayStudInfo[indexPath.row]["Email"] as? String
        cell.btnEdit.tag = indexPath.row
        cell.btnDelete.tag = indexPath.row


    //        cell.btnDelete.addTarget(self, action: Selector("btn_Delete_Clicked"), forControlEvents: UIControlEvents.TouchUpInside )
    //        cell.btnEdit.addTarget(self, action: Selector("btn_Edit_Clicked"), forControlEvents: UIControlEvents.TouchUpInside)

        cell.btnEdit.addTarget(self, action: #selector(ViewController.btn_Delete_Clicked (_:)), forControlEvents: UIControlEvents.TouchUpInside)
        cell.btnEdit.addTarget(self, action: #selector(ViewController.btn_Edit_Clicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)

        return cell
    }


    // Edit Button Clicked
    @IBAction func btn_Edit_Clicked(sender: UIButton)
    {
        let updateView = self.storyboard?.instantiateViewControllerWithIdentifier("UpdateScreen") as! UpdateScreen

        print("Sender.Tag  = \(sender.tag)")
        updateView.strEmail = arrayStudInfo[sender.tag]["Email"] as? String
        updateView.dictRecord = (arrayStudInfo[sender.tag] as! NSDictionary)
        self.navigationController?.pushViewController(updateView, animated: true)
    }


    //Delete Button Clicked
    @IBAction func btn_Delete_Clicked(sender: UIButton)
    {
        let contactDB = FMDatabase(path: databasepath as String)

        let strDelete = arrayStudInfo[sender.tag]["Email"] as? String

        if contactDB.open()
        {
            let deleteSQL = "DELETE FROM StudentData WHERE Email='\(strDelete!)'"

            let result = contactDB.executeUpdate(deleteSQL, withArgumentsInArray: nil)
            if !result
            {
                print("Error: \(contactDB.lastErrorMessage())")
            }
            else
            {
                print("Deleted Record.")
                listAllData()
            }
        }
        else
        {
            print("Error: \(contactDB.lastErrorMessage())")
        }
        contactDB.close()
    }


    func listAllData()
    {
        arrayStudInfo.removeAllObjects();

        let contactDB = FMDatabase(path: databasepath as String)

        if contactDB.open()
        {
            let filemgr = NSFileManager.defaultManager()
            let dirpath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
            let docdir = dirpath[0] as String
            databasepath = docdir.stringByAppendingString("StudentDataManipulation.sqlite");

            if filemgr.fileExistsAtPath(databasepath as String)
            {
                let contactDB = FMDatabase(path: databasepath as String)

                if contactDB == nil
                {
                    print("Error: \(contactDB.lastErrorMessage())")
                }

                if contactDB.open()
                {
                    let sql_stmt = "CREATE TABLE IF NOT EXISTS StudentData (Name TEXT, Phone TEXT, Email TEXT PRIMARY KEY  NOT NULL, Comment TEXT)"

                    if !contactDB.executeStatements(sql_stmt)
                    {
                        print("Error: \(contactDB.lastErrorMessage())")
                    }

                    let SelectQuery = "SELECT * FROM StudentData"

                    if let results:FMResultSet? = contactDB.executeQuery(SelectQuery, withArgumentsInArray: nil)
                    {
                        while results?.next() == true
                        {
                            let dictRecord = results?.resultDictionary()
                            arrayStudInfo.insertObject(dictRecord!, atIndex: arrayStudInfo.count)

                            print("\nRESULT : \(results?.resultDictionary())")
                        }

                        HomeTableView.reloadData()
                    }
                    else
                    {
                        print("Recored not found");
                    }

                    contactDB.close()
                }
                else
                {
                    print("Error: \(contactDB.lastErrorMessage())")
                }
            }

            contactDB.close()
        }
        else
        {
            print("Error: \(contactDB.lastErrorMessage())")
        }
    }

    /*
    func listAllData()
    {
        arrayStudInfo.removeAllObjects();

        let contactDB = FMDatabase(path: databasepath as String)

        if contactDB.open()
        {
            let SelectQuery = "SELECT * FROM StudentData"

            if let results:FMResultSet? = contactDB.executeQuery(SelectQuery, withArgumentsInArray: nil)
            {
                while results?.next() == true
                {
                    let dictRecord = results?.resultDictionary()
                    arrayStudInfo.insertObject(dictRecord!, atIndex: arrayStudInfo.count)

                    print("\nRESULT : \(results?.resultDictionary())")
                }

                HomeTableView.reloadData()

            }
            else
            {
                print("Recored not found");
            }
            contactDB.close()
        }
        else
        {
            print("Error: \(contactDB.lastErrorMessage())")
        }
    }
    */
}
1
this error indicate of out of index please check break point and your index number in array size. - Bhadresh Kathiriya
Yes , this error only comes on Clicking the Edit button in below block, delete and insert operation work fine , code showing below, @IBAction func btn_Edit_Clicked(sender: UIButton) { let updateView = self.storyboard?.instantiateViewControllerWithIdentifier("UpdateScreen") as! UpdateScreen print("Sender.Tag = (sender.tag)") updateView.strEmail = arrayStudInfo[sender.tag]["Email"] as? String updateView.dictRecord = (arrayStudInfo[sender.tag] as! NSDictionary) self.navigationController?.pushViewController(updateView, animated: true) } - Hardik Chavda
you might want to check this line: arrayStudInfo.insertObject(dictRecord!, atIndex: arrayStudInfo.count) is this line working good? - Devang Tandel
yes line: arrayStudInfo.insertObject(dictRecord!, atIndex: arrayStudInfo.count) is working fine - Hardik Chavda
Getting Error in Method: @IBAction func btn_Edit_Clicked(sender: UIButton) { - Hardik Chavda

1 Answers

0
votes

With these two lines:

        cell.btnEdit.addTarget(self, action: #selector(ViewController.btn_Delete_Clicked (_:)), forControlEvents: UIControlEvents.TouchUpInside)
        cell.btnEdit.addTarget(self, action: #selector(ViewController.btn_Edit_Clicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)

You are binding two actions to cell.btnEdit. When you tap the btnEdit, first, ViewController.btn_Delete_Clicked(_:) is executed, and one entry of your data deleted, and then ViewController.btn_Edit_Clicked(_:) is executed. At that time, arrayStudInfo[sender.tag] is not available, as, you see, already deleted.

Considering each cells may be re-used, the two line above needs to be something like this:

        cell.btnDelete.removeTarget(nil, action: nil, forControlEvents: .TouchUpInside)
        cell.btnDelete.addTarget(self, action: #selector(ViewController.btn_Delete_Clicked (_:)), forControlEvents: .TouchUpInside)
        cell.btnEdit.removeTarget(nil, action: nil, forControlEvents: .TouchUpInside)
        cell.btnEdit.addTarget(self, action: #selector(ViewController.btn_Edit_Clicked(_:)), forControlEvents: .TouchUpInside)

Please try.