开发者

Question about creating a UITextField programmatically

I have two classes:

  • RootViewController.h
  • RootViewController.m

In my RootViewController.h

// in .h file 
UITextField* myTextField_;

@property (nonatomic, retain) UITextField* myTextField.

In my RootViewController.m

// in .m file
@synthesize myTextField = myTextField_

// in dealloc
[myTextField_ release]


// in viewDidLoad
UITextField* tf  = [[UITextField alloc] init] initWithFrame:CGRectMake(200,6,100,30)];
[nameTextField_ = tf];
[tf release]

My question is, Does that create any memory leaks? Or will that crash? Are there better ways to create an instance of UITextField so I keep a reference to it? Perhaps

myTextField_ = [[UITextField alloc] init] initWithFrame:CGRectMak开发者_开发知识库e(200,6,100,30)];

would that be sufficient?


The simpliest way is to do this like this:

.h:

UITextField *myTextField;
@property (nonatomic, retain) UITextField *myTextField;

.m

@synthesize myTextField;

- (void)viewDidLoad {
    myTextField = [[UITextField alloc] initWithFrame:CGRectMake(200,6,100,30)];
}

- (void)dealloc {
    [myTextField release];
}

You will have one instance which is allocated and released in most clean way and you will have reference to this textfield all the time.


You should not do [tf release] as you are accessing your variable directly.

If you access it via self. notation that it will be called [tf retain] and then you should release tf. So in your current version all is ok besides line where you are releasing.


[nameTextField_ = tf];


change:

[self setMyTextField:tf]


Yes, this will do:

myTextField_ = [[UITextField alloc] initWithFrame:CGRectMake(200,6,100,30)];

You can also use this:

self.myTextField = [[UITextField alloc] initWithFrame:CGRectMake(200,6,100,30)] autorelease]; 

(when using the property it will retain, when using directly the member myTextField_ it won't (automatically) retain). Also alloc will set retainCount to 1 so it will eventually need to be released (in your case in dealloc method you can use either [myTextField_ release]; or self.myTextField=nil;);

Not sure what this is (I believe it will show up some compile errors): [nameTextField_ = tf];

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜