4

I have the following code inside my UIViewController -

[flipButton addTarget:self.navigationController.delegate action:@selector(changeModeAction:) forControlEvents:UIControlEventTouchUpInside];

As you can see, it calls a method inside it's navigation controller delegate. How do I correctly pass along an object to this method?

skålfyfan
  • 4,931
  • 5
  • 41
  • 59

4 Answers4

11

You can use the layer property. Add the object you want to pass as the value in the layer dictionary.

[[btn layer] setValue:yourObj forKey:@"yourKey"];

This yourObj is accessible from the button action function:

-(void)btnClicked:(id)sender
{
    yourObj = [[sender layer] valueForKey:@"yourKey"];
}

With this method you can pass multiple values to the button function just by adding new objects in the dictionary with different keys.

kratenko
  • 7,354
  • 4
  • 36
  • 61
Tinku George
  • 585
  • 5
  • 14
2

Or you can use objc_setAssociatedObject and objc_getAssociatedObject

Henning
  • 2,710
  • 2
  • 17
  • 16
1

When changeModeAction: is called flipButton should pass itself as the sender. If you need additional parameters passed you could create a category for the type of flipButton to store additional information or you could set up a dictionary that the navigationController can access e.g.

if(sender == flipButton)
 id obj = [someDictionary objectForKey:@"flipButtonKey"];
Community
  • 1
  • 1
Joe
  • 56,979
  • 9
  • 128
  • 135
0

extension + Swift 3.0

extension NSObject {

fileprivate struct ObjectTagKeys {
    static var ObjectTag = "ObjectTag"
}

func setObjectTag(_ tag:Any!) {
    objc_setAssociatedObject(self, &ObjectTagKeys.ObjectTag, tag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}

func getObjectTag() -> Any
{
    return objc_getAssociatedObject(self, &ObjectTagKeys.ObjectTag)
}

}
Chen Jiling
  • 519
  • 5
  • 10