(Target: Object) not working for setting UIButton

2019-09-02 12:09发布

问题:

I can create the UIButton.
But the callback: target: object won't work within the current object. ??
I can only do "self.viewController" object, and can't do "self" for current object.

thx


#import <Foundation/Foundation.h>
#import "ViewController.h"

@class ViewController;

@interface CGuiSetup : NSObject
{
    @public
    ViewController *viewController;
}
- (void) Setup;
- (void) ButtonRespond:(UIButton*) btn;
@end

#import "CGuiSetup.h"

@implementation CGuiSetup

- (void) ButtonRespond:(UIButton*) btn
{
    NSLog(@"ButtonRespond");
}


- (void) Setup
{

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn setFrame:CGRectMake(10,10,100,100)];

    // But I want to call the following in the CGuiSetup object (self) instead... but it crashes out if I leave it as just "self"
    [btn addTarget:self.viewController action:@selector(ButtonRespond:)
        forControlEvents:UIControlEventTouchUpInside]; //works: for "self.viewController" if I put ButtonRespond in the ViewController

    [btn addTarget:self action:@selector(ButtonRespond:)
        forControlEvents:UIControlEventTouchUpInside]; //fails: for "self"

    [self.viewController.view addSubview:btn];
}
@end

#import <UIKit/UIKit.h>
#import "CGuiSetup.h"

@class CGuiSetup;

@interface ViewController : UIViewController
{
    CGuiSetup *guiSetup; //<---- had to take this out of the "viewDidLoad" method
}
@end

- (void)viewDidLoad
{
    [super viewDidLoad];

    guiSetup = [CGuiSetup alloc];
    guiSetup->viewController = self;


    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn setFrame:CGRectMake(10,10,100,100)];
    [btn addTarget:guiSetup action:@selector(ButtonRespond:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];

}

回答1:

If you're using ARC, does any object have a retaining reference to CGuiSetup? I sounds like CGuiSetup is instantiated, creates (or maybe receives from another object) the viewController, adds the button to it and then gives the view controller to another object (perhaps by pushing it on a navController or setting it to be the root controller of the app)? Whatever the case is, CGuiSetup it being dealloc'd and the button is trying to send a message to an object that's already been destroyed. How/where is CGuiSetup created? What object retains a reference to it? That's probably where your problem is.

If you don't understand what retain/release is and/or you don't know what ARC is, you need to read Apple's memory management guide: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html



回答2:

That's probably because your object is destroyed, while _viewController still has retain count greater than 0 (so it's not destroyed). Balance you're retain/release count.