简体   繁体   中英

NULL properties inside event handler (cocoa app)

I have a class with several IBOtlets:

@interface MainDreamer : NSWindow <NSWindowDelegate>
{    
    IBOutlet NSTextField *dreamField;
    IBOutlet NSTableView *dreamTable;    
    IBOutlet NSImageView *dreamview;

    IBOutlet NSMutableArray *dreamlist;  
    IBOutlet NSMutableArray *dataset;
}

Everything is all right, but only in mouseUp event handler:

- (void) mouseUp:(NSEvent *)theEvent{
    [super mouseUp:theEvent];
    long index = [dreamTable selectedRow];
    Dream *dr = [dataset objectAtIndex:index];
    dr.dreampicture = dreamview.image;
    [dataset replaceObjectAtIndex:index withObject:dr];
}

all of them turn into NULL.

How to get access to IBOutlets inside event handler?

How to get access to IBOutlets inside event handler?

You already have it. Outlets are just instance variables (or properties, if you declare them as such); there is nothing special about outlets or responder methods that causes one to not work in the other.

So then why do your outlets appear connected in some parts of your code and hold nil in others?

Usually, this is because you have created a MainDreamer object in the nib and created one in code, or you have created it in two separate nibs.

Either way, that makes two objects of the same class. They are not the same object, and one has its outlets connected and the other doesn't. The one you are clicking on is not the one you created and hooked up in the nib (or one of the nibs).

The way to prove this would be to log self both in the mouseUp: method and in any place where you've found the outlets to be connected. I expect you will find different values of self : as I said, two objects.

The solution is to remove one of the instances and change all uses of it to use the other instead. If you are creating one of the objects in code, that is the one you should remove, in favor of the one in the nib.

If mouseUp is a method in your MainDreamer object, the properties should be available. Are you sure you've correctly connected all the outlets in Interface Builder? Try adding this to your object:

- (void)awakeFromNib {
    NSLog("table: %@", dreamTable);
    NSLog("view: %@", dreamview);
    NSLog("dataset: %@", dataset);
}

If they are null you don't have them connected properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM