ripa ripa - 3 months ago 18
Swift Question

get primary key of selected tableview row from realm db in swift

I'm developing an app using realm and swift. I've an btrInfo object.
I'm showing btrInfo as a uitableview. and in uitableview, "hjemmelshaverr" is displaying as row content. btrInfo object data is below:-

Results<btrInfo> (
[0] btrInfo {
overskriftt = Test 1;
hjemmelshaverr = Test 1 hi;
id = 1;
},
[1] btrInfo {
overskriftt = Test 2;
hjemmelshaverr = Test 2;
id = 2;
},
[2] btrInfo {
overskriftt = Test 3;
hjemmelshaverr = Test 3 haggard;
id = 3;
}
)


now I'm not able to get id when one row will be selected. I can get table row index but not id. Here id is the primary key.

Searching it from 1 hour. but didn't get any proper answer.
any help would be appreciated.

<<< EDIT >>>>>>

self.table1Data contains below:-

[Test 1 hi, Test 2, Test 3 haggard]



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

let cell = table1.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

cell.textLabel!.text = self.table1Data[indexPath.item] as? String

// print(indexPath.item)
//cell.contentView = table1Data[indexPath.item]


return cell
}

// add custom style
func tableView(table1: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {



// 1
let shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Edit" , handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in

print(indexPath.item)
// 2
let shareMenu = UIAlertController(title: nil, message: "Do You want to Edit", preferredStyle: .ActionSheet)

let twitterAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)

shareMenu.addAction(twitterAction)
shareMenu.addAction(cancelAction)


self.presentViewController(shareMenu, animated: true, completion: nil)

self.editReport(indexPath.item)
})






// 7

shareAction.backgroundColor = UIColor.blueColor()

return [shareAction]
}

Answer

do like

Step-1

create one array of Dictionary like

var table1Data: [[String : AnyObject]] = ()

step-2

 override func viewDidLoad() { 
super.viewDidLoad() 

// Initiate realm 
let realm = try! Realm() 

 table1Data = realm.objects(btrInfo) 
}

Step-3

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

    let cell = table1.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

    cell.textLabel!.text = self.table1Data[indexPath.item]["hjemmelshaverr"] as? String


    return cell
}

step-4

call like

    self.presentViewController(shareMenu, animated: true, completion: nil)

        self.editReport(self.table1Data[indexPath.item]["id"] as? String)