0

Possible Duplicate:
Understanding when to call retain on an object?

I have a hard time to understand when I have to retain an object? Is there a general rule?

For example:

- (IBAction)buttonPressed:(UIButton *)button{

    // some code

    NSString *buttonText = button.titleLabel.text;
    //retain needed or not ?
    [buttonText retain];
    double result = [someObject someMethod:buttonText];

    // some more code
}
Community
  • 1
  • 1
Stefan Arn
  • 1,156
  • 12
  • 29
  • 6
    I suggest thoroughly reading the [Objective-C Memory Management Guide](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html) that Apple created. Also, this question seems to be an exact duplication of [this question](http://stackoverflow.com/questions/4450644/understanding-when-to-call-retain-on-an-object). – CIFilter Sep 21 '11 at 14:31

2 Answers2

0
- (IBAction)buttonPressed:(UIButton *)button{

// some code

NSString *buttonText = [button.titleLabel.text retain];
//retain needed or not ?
// if you think your code can release the button object at this point, so you have to retain it.
// like : 
//[button release];

// its safer to retain your object so there wont be any problem. And dont forget to release

//[buttonText retain];


double result = [someObject someMethod:buttonText];

// release when you done with it.
[buttonText release];

// some more code
}
ymutlu
  • 6,585
  • 4
  • 35
  • 47
0

In that case you don't have to retain buttonText unless you're going to release the button and you need to keep the string. Retain increments the retain count of the object, and there are some rules and conventions to use it. I recommend you to read this

Also take a look in Apple's Documentation, there's a lot of literature on this topic.

Youssef
  • 3,582
  • 1
  • 21
  • 28