Swift crashes after TableViewCell pressed - ios

My app keeps crashing when I select the TableViewCell but it does not give me an error message. Hope some on can help. Below is the TableView Controller and the View Controller code. I have added the date into the cordite model and think it has something to do with that.
import UIKit
import CoreData
class DiveLogTableViewController: UITableViewController {
var myDivelog : Array<AnyObject> = []
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewDidAppear(animated: Bool) {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
let freq = NSFetchRequest(entityName: "Divelog")
myDivelog = context.executeFetchRequest(freq, error: nil)!
tableView.reloadData()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "update" {
var selectedItem: NSManagedObject = myDivelog[self.tableView.indexPathForSelectedRow()!.row] as! NSManagedObject
let ADLVC: AddDiveLogViewController = segue.destinationViewController as! AddDiveLogViewController
ADLVC.divenumber = selectedItem.valueForKey("divenumber") as! String
ADLVC.ddate = selectedItem.valueForKey("ddate") as! NSDate
ADLVC.divelocation = selectedItem.valueForKey("divelocation") as! String
ADLVC.existingItem = selectedItem
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return myDivelog.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellID: NSString = "Cell"
var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(CellID as String) as! UITableViewCell
if let ip = indexPath as NSIndexPath? {
var data: NSManagedObject = myDivelog[ip.row] as! NSManagedObject
var ddate = data.valueForKey("ddate") as! NSDate
var diveloc = data.valueForKey("divelocation") as! String
var diveno = data.valueForKey("divenumber") as! String
cell.textLabel!.text = "#\(diveno)#\(diveloc)"
cell.detailTextLabel!.text = "\(ddate),location: \(diveloc)"
}
// Configure the cell...
return cell
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
if editingStyle == UITableViewCellEditingStyle.Delete {
if let tv = tableView as UITableView? {
context.deleteObject(myDivelog[indexPath.row] as! NSManagedObject)
myDivelog.removeAtIndex(indexPath.row)
tv.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
}
var error: NSError? = nil
if !context.save(&error) {
abort()
}
}
}
}
import UIKit
import CoreData
class AddDiveLogViewController: UIViewController {
#IBOutlet weak var textFieldDiveNumber: UITextField!
#IBOutlet weak var textFieldDiveLocation: UITextField!
#IBOutlet weak var textFieldDDate: UITextField!
var divenumber: String = ""
var divelocation: String = ""
var ddate = NSDate()
var datePickerView: UIDatePicker!
var existingItem: NSManagedObject!
override func viewDidLoad() {
super.viewDidLoad()
if (existingItem != nil) {
textFieldDiveNumber.text = divenumber
textFieldDiveLocation.text = divelocation
textFieldDDate.text = ddate.stringValue
}
// Do any additional setup after loading the view.
datePickerView = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.Date
var toolbar = UIToolbar(frame: CGRectMake(0, 0, datePickerView.frame.width, 44))
let OKButton = UIBarButtonItem(title: "OK", style: .Plain, target: self, action: "OKButtonTapped:")
toolbar.setItems([OKButton], animated: true)
self.textFieldDDate.inputView = datePickerView
self.textFieldDDate.inputAccessoryView = toolbar
}
#IBAction func saveTapped(sender: AnyObject) {
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let contxt: NSManagedObjectContext = appDel.managedObjectContext!
let en = NSEntityDescription.entityForName("Divelog", inManagedObjectContext: contxt)
if (existingItem != nil) {
existingItem.setValue(textFieldDiveNumber.text, forKey: "divenumber")
existingItem.setValue(textFieldDiveLocation.text, forKey: "divelocation")
existingItem.setValue(textFieldDDate.text.dateValue!, forKey: "ddate")
} else {
var newItem = Divelog(entity: en!, insertIntoManagedObjectContext: contxt)
newItem.divenumber = textFieldDiveNumber.text
newItem.divelocation = textFieldDiveLocation.text
newItem.ddate = textFieldDDate.text.dateValue!
}
contxt.save(nil)
self.navigationController?.popToRootViewControllerAnimated(true)
}
#IBAction func cancelTapped(sender: AnyObject) {
self.navigationController?.popToRootViewControllerAnimated(true)
}
func OKButtonTapped(sender: UIBarButtonItem) {
self.textFieldDDate.endEditing(true)
self.textFieldDDate.text = datePickerView.date.stringValue
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Related

Value of type "Entity" has no member 'text'

I am making a basic note taking app. I cannot seem to change the text of my attributes in my code. Any advice?
import UIKit
import CoreData
class NoteInputTableViewController: UITableViewController, UINavigationControllerDelegate {
var listItem: List?
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
#IBOutlet weak var inputNoteLabel: UITextField!
func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
if let item = listItem {
listItem.text = inputNoteLabel.text
} else {
let newItem = NSEntityDescription.insertNewObjectForEntityForName("List", inManagedObjectContext: managedObjectContext) as! List
newItem.text = inputNoteLabel.text
}
if let controller = viewController as? NoteHomeTableViewController {
controller.items = [items!]
}
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.delegate = self
} // viewDidLoad end
}
In my navigationController I am attempting to change the text of my listItem, but cannot seem to do so.
Below is my List+CoreDataProperties.swift file:
import Foundation
import CoreData
extension List {
#NSManaged var note: String?
#NSManaged var completionDate: NSDate?
}
And below is my NoteHomeTableViewController.swift file:
import UIKit
import CoreData
class NoteHomeTableViewController: UITableViewController, MyCellDelegate { // will need a delegate
var items: [List] = []
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
#IBAction func composeButtonPressed(sender: UIBarButtonItem) {
performSegueWithIdentifier("CellDetailSegue", sender: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destination = segue.destinationViewController as! NoteInputTableViewController
if let ip = sender as? NSIndexPath {
destination.listItem = items[ip.row]
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as! MyCell
cell.indexPath = indexPath
cell.item = items[indexPath.row]
cell.delegate = self
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
performSegueWithIdentifier("CellDetailSegue", sender: indexPath)
}
func myCell(myCell: MyCell, didPressBackItem: List,
atIndexPath indexPath: NSIndexPath) {
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let item = items[indexPath.row]
managedObjectContext.deleteObject(item)
do {
try managedObjectContext.save()
} catch {
print("error saving")
}
fetchItems()
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
} // viewDidLoad end
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
fetchItems()
tableView.reloadData()
} // viewDidAppear end
func fetchItems() {
let request = NSFetchRequest(entityName: "List")
items = []
do {
let response = try managedObjectContext.executeFetchRequest(request) as! [List]
for item in response {
items.append(item)
}
} catch {
print("Error fetching data!")
}
} // fetch end
} // class end
I don't see where you initialize listItem.
I suggest
} else {
let newItem = NSEntityDescription.insertNewObjectForEntityForName("List", inManagedObjectContext: managedObjectContext) as! List
newItem.text = inputNoteLabel.text
}
should probably become
} else {
let newItem = NSEntityDescription.insertNewObjectForEntityForName("List", inManagedObjectContext: managedObjectContext) as! List
listItem = newItem
newItem.text = inputNoteLabel.text
}
Use the unwrapped item after the optional binding and assign the new initialized NSManagedObject to listItem
...
if let item = listItem {
item.text = inputNoteLabel.text
} else {
listItem = NSEntityDescription.insertNewObjectForEntityForName("List", inManagedObjectContext: managedObjectContext) as! List
listItem!.text = inputNoteLabel.text
...
or easier
...
if listItem == nil {
listItem = NSEntityDescription.insertNewObjectForEntityForName("List", inManagedObjectContext: managedObjectContext) as! List
}
listItem!.text = inputNoteLabel.text
...

Bar Button Nil After Pressing Switch in Swift?

Ok here is what is going on. I have a table view class called MainTabeViewController. I have a sidebar class called SettingsSidebarViewController that uses SW Reveal to show a menu. The menu is toggled by a bar button item called settings. The menu works fine with the bar button item, and when you press it the menu toggles like it should.
However, once I click a switch, the app crashes and I start getting a EXC_BAD_INSTRUCTION error that reads in the console Fatal error: unexpectedly found nil while unwrapping an optional value. Why is the bar button item suddenly nil after the switch is pressed?
MAINTABLEVIEWCONTROLLER.swift
import UIKit
import SwiftyJSON
class MainTableViewController: UITableViewController, SettingsSidebarViewDelegate {
//HEERE IS THE BAR BUTTON ITEM CALLED SETTINGS <- <- <-
#IBOutlet var settings: UIBarButtonItem!
var NumberofRows = 0
var names = [String]()
var descriptions = [String]()
var categories = [String]()
var types = [String]()
var series = [String]()
var groups = [String]()
func parseJSON(){
let path = NSBundle.mainBundle().URLForResource("documents", withExtension: "json")
let data = NSData(contentsOfURL: path!) as NSData!
let readableJSON = JSON(data: data)
NumberofRows = readableJSON["Documents"].count
for i in 1...NumberofRows {
let doc = "Doc" + "\(i)"
let Name = readableJSON["Documents"][doc]["name"].string as String!
let Description = readableJSON["Documents"][doc]["description"].string as String!
let Category = readableJSON["Documents"][doc]["category"].string as String!
let Type = readableJSON["Documents"][doc]["type"].string as String!
let Series = readableJSON["Documents"][doc]["tags"]["series"].string as String!
let Group = readableJSON["Documents"][doc]["tags"]["group"].string as String!
names.append(Name)
descriptions.append(Description)
categories.append(Category)
types.append(Type)
series.append(Series)
groups.append(Group)
}
}
Here is where the errors start to occur AFTER the switch is pressed (still in same class)
func initSettings(){
//Sets button title to gear, sets button actions (to open menu)
settings.title = NSString(string: "\u{2699}\u{0000FE0E}") as String!
let font = UIFont.systemFontOfSize(25);
settings.setTitleTextAttributes([NSFontAttributeName: font], forState:UIControlState.Normal)
settings.target = self.revealViewController()
settings.action = #selector(SWRevealViewController.rightRevealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
func showTags(showTags: Bool) {
tableView.reloadData()
}
func showTimestamp(showTimeStamp: Bool) {
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
parseJSON()
initSettings()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return NumberofRows
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MainTableCell", forIndexPath: indexPath) as! MainTableViewCell
if names.count != 0{
cell.fileName.text = names[indexPath.row]
cell.fileDescription.text = descriptions[indexPath.row]
cell.fileCategory.text = categories[indexPath.row]
cell.fileType.text = types[indexPath.row]
cell.options.setTitle(NSString(string: ":") as String!, forState: .Normal)
cell.tag1.text = series[indexPath.row]
cell.tag2.text = groups[indexPath.row]
if showTagsVal{
cell.tag1.hidden = false
}
else{
cell.tag1.hidden = true
}
if showTimeStampVal{
cell.tag2.hidden = false
}
else{
cell.tag2.hidden = true
}
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("showView", sender: self)
}
// MARK: - Navigation
//In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "showView"){
let detailVC: DetailViewController = segue.destinationViewController as! DetailViewController
let indexPath = self.tableView.indexPathForSelectedRow!
detailVC.text = names[indexPath.row]
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}}}
SettingsSidebarViewController.swift
import UIKit
protocol SettingsSidebarViewDelegate{
func showTags(showTags: Bool);
func showTimestamp(showTimeStamp: Bool)
}
var showTagsVal = false
var showTimeStampVal = false
class SettingsSidebarViewController: UIViewController {
var delegate: SettingsSidebarViewDelegate! = nil
#IBOutlet weak var sidebar_title: UILabel!
#IBOutlet var showTagsSwitch: UISwitch!
#IBOutlet var showTimestampSwitch: UISwitch!
#IBAction func switchPressed(sender: AnyObject) {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("main") as! MainTableViewController
self.presentViewController(nextViewController, animated:true, completion:nil)
let vc = MainTableViewController()
self.delegate = vc
if showTagsSwitch.on{
showTagsVal = true
delegate.showTags(showTagsVal)
}
else{
showTagsVal = false
delegate.showTags(showTagsVal)
}
if showTimestampSwitch.on{
showTimeStampVal = true
delegate.showTimestamp(showTimeStampVal)
}
else{
showTimeStampVal = false
delegate.showTimestamp(showTimeStampVal)
}
}
override func viewDidLoad() {
super.viewDidLoad()
sidebar_title.text = "Settings"
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
Help is appreciated! I am sure this is a question concerning transitioning view controllers that is something easy but I have tried too long to figure it out.
Your problem is you are creating a new instance of MainTableViewController and assigning it to delegate. That's why the bar button item is nil, because all the initialization and binding isn't done.
You have to change the delegate and assign the view controller you already got with instantiateViewControllerWithIdentifier:
self.delegate = nextViewController

How to set CustomTableView immediately (CoreData)

I have a TextField, Button and a TableView in ViewController
I press Button -> import Text to Data and also export to TableView
But it does not work
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
myTableView.reloadData()
}
#IBOutlet weak var txtClient: UITextField!
#IBAction func butNhap(sender: AnyObject) {
var newName = txtClient.text as String
var myDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var myContext: NSManagedObjectContext = myDelegate.managedObjectContext!
var myText: AnyObject = NSEntityDescription.insertNewObjectForEntityForName("Client", inManagedObjectContext: myContext)
myText.setValue(newName, forKey: "name")
txtClient.text = ""
}
#IBOutlet weak var myTableView: UITableView!
var exportArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.myTableView.delegate = self
self.myTableView.dataSource = self
myTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "myCell")
}
func export() -> [String] {
var myDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var myContext: NSManagedObjectContext = myDelegate.managedObjectContext!
var exportName = NSFetchRequest(entityName: "Client")
exportName.returnsObjectsAsFaults = false
var exportValue = myContext.executeFetchRequest(exportName, error: nil)
for result: AnyObject in exportValue! {
exportArray.insert((result.valueForKey("name") as! String), atIndex: 0)
}
return exportArray
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = exportArray[indexPath.row]
return cell
}
}
Create one custom UITableviewcell and give name and identifier it like "customtableCell", then on the respective view controller you have to register that custom cell,
let nibName = UINib(nibName: "customtableCell", bundle:nil)
tblConnect!.registerNib(nibName, forCellReuseIdentifier: "customtableCell")
After that on the cellForRowAtIndexPath use below type of code,
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let identifier = "customtableCell"
var tablecell: customtableCell!
if (tablecell == nil) {
tablecell = tableView.dequeueReusableCellWithIdentifier(identifier) as? customtableCell
}
return tablecell
}

PopOver TableView, error at cell in Swift IOS 8

i am using ViewController in my application. in ViewController i try to popOver tableview using textfield. but having error
this my code popUp :
Func textFieldShouldBeginEditing(textField: UITextField) -> Bool{
if (textField == paymentTextField){
var paymentVC = MasterPaymentTableViewController()
paymentVC.modalPresentationStyle = .Popover
paymentVC.preferredContentSize = CGSizeMake(300, 500)
let popOverPresentationVC = paymentVC.popoverPresentationController
popOverPresentationVC?.delegate = self
popOverPresentationVC?.permittedArrowDirections = .Down
popOverPresentationVC?.sourceView = textField as UIView
self.navigationController?.presentViewController(paymentVC, animated: true, completion: nil)
return false
}
}
this error at code :
import UIKit
import CoreData
class MasterPaymentTableViewController: UITableViewController {
var myList : Array<AnyObject> = []
var appDel : AppDelegate!
var context : NSManagedObjectContext!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
appDel = UIApplication.sharedApplication().delegate as! AppDelegate
context = appDel.managedObjectContext
let freq = NSFetchRequest(entityName: "PayMethod")
myList = context.executeFetchRequest(freq, error: nil)!
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell {
let cellID : String = "Cell"
// ERROR AT HERE : unexpectedly found nil while unwrapping an Optional value
var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! UITableViewCell
// -------------
if let ip = indexPath {
var myObject : NSManagedObject = myList[ip.row] as! NSManagedObject
let title = myObject.valueForKeyPath("paymentName") as! String
cell.textLabel!.text = title
}
return cell
}
But, if i open tableView directly not from popOver, its working normal
any solution?
thx
Try this:
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
and use the dequeueReusableCellWithIdentifier:forIndexPath: method instead of using dequeueReusableCellWithIdentifier:
let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath:indexPath)

Swift Use of Unresolved Identifier 'IndexPath' TableView Cell Button

I am attempting to get the text of my UILabel and set it to my Parse object, but I am running into an issue setting the object to the index path of the cell. I am getting an Use of unresolved identifier 'indexPath' error at that line.
follow["following"] = self.userArray.objectAtIndex(IndexPath.row)
Here is my tableview controller:
import UIKit
class SearchUsersRegistrationTableViewController: UITableViewController {
var userArray : NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
var user = PFUser.currentUser()
loadParseData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: SearchUsersRegistrationTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! SearchUsersRegistrationTableViewCell
let row = indexPath.row
var individualUser = userArray[row] as! PFUser
var username = individualUser.username as String
var profileImage = individualUser["profileImage"] as? PFFile
if profileImage != nil {
profileImage!.getDataInBackgroundWithBlock({
(result, error) in
cell.userImage.image = UIImage(data: result)
})
} else {
cell.userImage.image = UIImage(named: "profileImagePlaceHolder")
}
cell.usernameLabel.text = username
cell.addUserButton.tag = row
cell.addUserButton.addTarget(self, action: "addUser:", forControlEvents: .TouchUpInside)
return cell
}
func loadParseData() {
var query : PFQuery = PFUser.query()
query.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]!, error:NSError!) -> Void in
if error == nil {
if let objects = objects {
println("\(objects.count) users are listed")
for object in objects {
self.userArray.addObject(object)
}
self.tableView.reloadData()
}
} else {
println("There is an error")
}
}
}
#IBAction func addUser(sender: UIButton) {
println("Button Triggered")
let addUserButton : UIButton = sender
let user : PFObject = self.userArray.objectAtIndex(addUserButton.tag) as! PFObject
var follow = PFObject(className: "Follow")
follow["following"] = self.userArray.objectAtIndex(IndexPath.row)
follow["follower"] = PFUser.currentUser().username
follow.saveInBackground()
}
}
Here is my tableview cell:
import UIKit
class SearchUsersRegistrationTableViewCell: UITableViewCell {
#IBOutlet weak var userImage: UIImageView!
#IBOutlet weak var usernameLabel: UILabel!
#IBOutlet weak var addUserButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
userImage.layer.borderWidth = 1
userImage.layer.masksToBounds = false
userImage.layer.borderColor = UIColor.whiteColor().CGColor
userImage.layer.cornerRadius = userImage.frame.width/2
userImage.clipsToBounds = true
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Try this
follow["following"] = self.userArray.objectAtIndex(sender.tag)
You are setting the row as tag for your button. Just use it.
you should not work with tags in that case.
to get the indexpath in your addUser function add the following:
let indexPath = tableView.indexPathForRowAtPoint(addUserButton.convertPoint(CGPointZero, toView: tableView))
then you can use that line:
follow["following"] = self.userArray.objectAtIndex(indexPath.row)
indexPath, not IndexPath

Resources