A. Edwards A. Edwards - 3 months ago 10x
iOS Question

EXC_BAD_ACCESS error when trying to access class variables sent from function

I am using a custom cell delegate to call a function when a button in the custom cell is pressed. I want to then change the image of the button to a particular image depending on a boolean variable of the custom cell class.

I am aware of how I can do this without delegation, however I also want to display an alert view when the button is pressed and I cannot do that within the custom cell class.

The problem I am running into is that I have a EXC_BAD_ACCESS error when trying to access the custom cell properties within the delegate function. Here is my code for my custom class:

import UIKit

protocol ProfileHeaderCellDelegate: class {
func follow(sender:ProfileHeaderCell)

class ProfileHeaderCell: UITableViewCell {

var followTapped = false
var delegate : ProfileHeaderCellDelegate!

@IBOutlet var profilePic: UIImageView!
@IBOutlet var followButton: UIButton!
@IBAction func followButtonTapped(sender: AnyObject) {


override func awakeFromNib() {
// Initialization code

self.profilePic.layer.cornerRadius = self.profilePic.frame.size.width / 2;
self.profilePic.clipsToBounds = true;

@IBOutlet var albumArt: UIImageView!
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)

// Configure the view for the selected state


And here is the function call from within the table view controller that contains the cell:

func follow(sender: ProfileHeaderCell){
if(sender.followTapped == false){
sender.followButton.imageView?.image = UIImage(named: "img1")
sender.followTapped = true
}else if(sender.followTapped == true){

let unfollowAlert = UIAlertController(title: "", message:"Would you like to unfollow this User?", preferredStyle: .Alert)
let unfollow = UIAlertAction(title: "Yes, Unfollow this User", style: .Destructive){(ACTION) in

print("unfollow tapped")
sender.followButton.imageView!.image = UIImage(named: "img2")

let cancel = UIAlertAction(title: "Cancel", style: .Cancel){(ACTION) in

print("cancel tapped")


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

The bad access error occurs on this first line of the delegate function:

if(sender.followTapped == false){

How can I properly access the variable from the custom cell object?


I realized that my mistake was within my cellForRowAtIndexPath method. The problem was that in addition to calling the delegate method when the button was tapped (through an IBAction in my custom cell class), I also had the following line in the cellForRowAtIndexPath method:

cell1.followButton.addTarget(self, action: "follow:", forControlEvents: .TouchUpInside)

I imagine the bad access was occurring because somehow the same "follow" method was being called, but from inside the main view controller which means the sender cell was never passed as a parameter.