What happens if I don't retain IBOutlet?

后端 未结 6 1492
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 16:13

If I do this:

@interface RegisterController : UIViewController 
{
    IBOutlet UITextField *usernameField;
}

ins

6条回答
  •  一生所求
    2020-11-29 16:55

    In fact there are two models:

    THE OLD MODEL

    These model was the model before Objective-C 2.0 and inherited from Mac OS X. It still works, but you should not declare properties to modify the ivars. That is:

    @interface StrokeWidthController : UIViewController {
        IBOutlet UISlider* slider;
        IBOutlet UILabel* label;
        IBOutlet StrokeDemoView* strokeDemoView;
        CGFloat strokeWidth;
    }
    @property (assign, nonatomic) CGFloat strokeWidth;
    - (IBAction)takeIntValueFrom:(id)sender;
    @end
    

    In this model you do not retain IBOutlet ivars, but you have to release them. That is:

    - (void)dealloc {
        [slider release];
        [label release];
        [strokeDemoView release];
        [super dealloc];
    }
    

    THE NEW MODEL

    You have to declare properties for the IBOutlet variables:

    @interface StrokeWidthController : UIViewController {
        IBOutlet UISlider* slider;
        IBOutlet UILabel* label;
        IBOutlet StrokeDemoView* strokeDemoView;
        CGFloat strokeWidth;
    }
    @property (retain, nonatomic) UISlider* slider;
    @property (retain, nonatomic) UILabel* label;
    @property (retain, nonatomic) StrokeDemoView* strokeDemoView;
    @property (assign, nonatomic) CGFloat strokeWidth;
    - (IBAction)takeIntValueFrom:(id)sender;
    @end
    

    In addition you have to release the variables in dealloc:

    - (void)dealloc {
        self.slider = nil;
        self.label = nil;
        self.strokeDemoView = nil;
        [super dealloc];
    }
    

    Furthermode, in non-fragile platforms you can remove the ivars:

    @interface StrokeWidthController : UIViewController {
        CGFloat strokeWidth;
    }
    @property (retain, nonatomic) IBOutlet UISlider* slider;
    @property (retain, nonatomic) IBOutlet UILabel* label;
    @property (retain, nonatomic) IBOutlet StrokeDemoView* strokeDemoView;
    @property (assign, nonatomic) CGFloat strokeWidth;
    - (IBAction)takeIntValueFrom:(id)sender;
    @end
    

    THE WEIRD THING

    In both cases, the outlets are setted by calling setValue:forKey:. The runtime internally (in particular _decodeObjectBinary) checks if the setter method exists. If it does not exist (only the ivar exists), it sends an extra retain to the ivar. For this reason, you should not retain the IBOutlet if there is no setter method.

提交回复
热议问题