bubbles
bubbles

Reputation: 881

Question about creating a UITextField programmatically

I have two classes:

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:CGRectMake(200,6,100,30)];

would that be sufficient?

Upvotes: 0

Views: 795

Answers (4)

alex-i
alex-i

Reputation: 5454

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];

Upvotes: 1

altchen
altchen

Reputation: 21

[nameTextField_ = tf];


change:

[self setMyTextField:tf]

Upvotes: 1

Bartek
Bartek

Reputation: 1996

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.

Upvotes: 3

Nekto
Nekto

Reputation: 17877

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.

Upvotes: 1

Related Questions