0

Sorry about my english...

in ".h" file

NSString *_name;

in ".m" file

-(id)init{

.....

_name = [[NSString alloc] initWithString:@"Hadrian"];

.....

}

and a function use to change the value of _name like this :

-(void) changeName:(NSString *)name{

    //No 1:

    _name = [name copy];

    //No 2:

    if(_name) [_name release];

    _name = [name copy];

}

No 1 cause leak? how to write this function standard?

Mikael
  • 3,572
  • 1
  • 30
  • 43

1 Answers1

0

Suggestions...

  • @property and @synthesize : If you use @property / @synthesize, getter/setters are handled by them. You don't need to handle it. (Use features instead of having long code)

    Look also answer from Inject IOS

    • Properties enforce access restrictions (such as readonly)
    • Properties enforce memory management policy (retain, assign)
    • Properties are (rarely) used as part of a thread safety strategy (atomic)
    • Properties provide the opportunity to transparently implement custom setters and getters.
    • Having a single way to access instance variables increases code readability.
  • Naming Conventions : Avoid _ prefixed to variable name to avoid conflicts with auto-generated accessor. Or else have synthesize as shown and explained at this link by Kelan

  • Leaks : You own the object when you alloc an object, or create a copy. This means you're given the object with a retain count of 1(not autoreleased). You are responsible and you should release it when you have used that object.

Community
  • 1
  • 1
βhargavḯ
  • 9,786
  • 1
  • 37
  • 59