1

正如标题中所写,我有一个UITextField. 我将此添加UITextFieldUIView.

如果我有一个强指针,UITextField就会出现,

如果我有一个弱指针,UITextField则不会出现。

当我有一个弱指针时出了什么问题?我做了同样的UIButton事情,然后它实际上出现了(带有强指针和弱指针)。

这是一些代码:

创建类别视图.h

@interface CreateCategoryView : UIView 

@property (weak, nonatomic) UITextField *nameTextField;

@end

创建类别视图.m

@implementation CreateCategoryView

- (id)initWithFrame:(CGRect)frame andParent {
    self = [super initWithFrame:frame];
    if (self) {
        self.nameTextField = [[UITextField alloc] initWithFrame:CGRectMake(5, 30, 310, 25)];
        self.nameTextField.borderStyle = UITextBorderStyleRoundedRect;
        self.nameTextField.textColor = [UIColor blackColor];
        self.nameTextField.backgroundColor = [UIColor whiteColor];
        [self addSubview:self.nameTextField];
    }
    return self;
}

@end
4

4 回答 4

5

您应该使用局部变量(默认为强变量)创建文本字段,然后将其分配给您的属性。没有必要使用对文本字段的强引用,因为您添加它以保持强引用的视图。

- (id)initWithFrame:(CGRect)frame  {
    self = [super initWithFrame:frame];
    if (self) {
        UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(5, 30, 310, 25)];
        tf.borderStyle = UITextBorderStyleRoundedRect;
        tf.textColor = [UIColor blackColor];
        tf.backgroundColor = [UIColor whiteColor];
        _nameTextField = tf;
        [self addSubview:_nameTextField];
    }
    return self;
}
于 2012-12-15T22:23:39.087 回答
3

接受的答案是错误的。

问题是视图在创建后立即被释放。您可以通过执行以下操作看到这一点

__weak UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];

有了这个,编译器会抱怨

warning: assigning retained object to weak variable; object will be released after assignment

您需要做的是有一个临时strong变量,正如@rdelmar 指出的那样,默认情况下局部变量是

所以

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];

相当于

__strong UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];

这将使视图保持足够长的时间以被视图调用所拥有addSubview

于 2012-12-15T22:45:34.840 回答
0

Apple 文档对此有一个示例

弱变量可能会造成混淆,尤其是在这样的代码中:

NSObject * __weak someObject = [[NSObject alloc] init];

在这个例子中,新分配的对象没有对其的强引用,所以它立即被释放并且 someObject 被设置为 nil。

于 2014-04-19T07:14:50.077 回答
-1

该对象不会保留,因为它是一个弱指针,因此您的文本字段在初始化后立即被释放。使用弱属性指向强对象,以便对象保持保留。

于 2012-12-15T21:43:04.320 回答