Caborca87
Caborca87

Reputation: 187

How do I access a pointer in multiple instance methods?

I do not understand how to declare an pointer that can be accessed in more than one method. The following code uses myContainer to store a number which is utilized when useMyContainer is called.

@interface MyViewController : UIViewController {
    NSString *myContainer;
    IBOutlet UILabel *display;
}
- (IBAction)storeToMyContainer: (UIButton *)sender;
- (IBAction)useMyContainer: (UIButton *)sender;
@end

@implementation MyViewController
- (IBAction)storeToMyContainer: (UIButton *)sender {
myContainer = sender.titleLabel.text;
}
- (IBAction)useMyContainer: (UIButton *)sender {
[someOtherClass doSomethingWith:[myContainer doubleValue]];
}
@end

What I don't understand is that when I use display in the same manner, I don't have a problem. What do I need to do to access myContainer in useMyContainer in this manner?

Some thoughts: I know this is a memory management issue, and I am almost sure that a retain is being called on display (probably by the .xib file?) and that is why display hangs around long enough to be used in both methods.

I know a work around that involves using a double and an int, but I consider this to be messy, and as I'm taking a class on this I wanna to know the baller way to handle this.

Thanks for your help!

Upvotes: 0

Views: 79

Answers (2)

Guven
Guven

Reputation: 2310

The proper way of handling this would be to take care of memory management for your 'myContainer' field.

I would go with:

myContainer = [sender.titleLabel.text copy];

It is recommended to use copy for NSString. Relevant thread for that discussion is here.

Also, please don't forget to release the memory for the 'myContainer' field. You can do that in your dealloc method:

-(void) dealloc {
    [myContainer release];
    [super dealloc];    
}

Upvotes: 1

user94896
user94896

Reputation:

You are correct in saying that this is a memory management issue. Basically, you're not "claiming ownership" of the string being stored in myContainer. Some (short) period of time after storeToMyContainer: is called, the autorelease pool containing the sender's string is drained and, because you didn't say that you're still using it, it ceases to exist.

To claim ownership of the string, you must retain (or copy) it. So, updating your code:

- (IBAction)storeToMyContainer:(UIButton *)sender {
    myContainer = [sender.titleLabel.text retain];
}

Another approach would be to use properties. Either way, I recommend you have a read over the Memory Management Programming Guide, specifically Basic Memory Management Rules.

Upvotes: 0

Related Questions