0

I am trying to create non-atomic copy accessors, and I read everywhere that the object should be released at the end. So, if you could help me understand whether I am doing it properly, I would appreciate it. Will the following be correct?

@interface ClassA: NSObject
{
   NSString* stringA;
}

@property (nonatomic, copy) NSString* stringA;

@implementation ClassA

@synthesize stringA;

-(void) setStringA: (NSString*) stringInput {
   if(stringA != stringInput) {
      [stringA release];
      stringA = [stringInput copy];
   }
}

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

I am looking for a confirmation whether I need to deallocate stringA in the dealloc method at the end and whether I did it correctly.

Many thanks.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Igor Tupitsyn
  • 1,193
  • 3
  • 18
  • 45

2 Answers2

1

You need to release it, yes. (You don't deallocate things. You release your ownership of them and they may be deallocated as a result.)

Your code is correct.

The rules are that you must release any object you receive from a method whose name begins with "alloc" or "new" or contains "copy". You also must release any object that you retain. Since you call -copy on stringInput, you are responsible for eventually releasing the object you receive from that.

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
1

@Ken Thomases is right; your code is correct. A few things, though:

You don't really need to declare the ivar, or synthesize the property, or write your own setter; all this is done for you. So your code (while correct) could be simplified to:

@interface ClassA: NSObject
@property (nonatomic, copy) NSString* stringA;
@end

@implementation ClassA

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

@end

Second, if you're using ARC (which I recommend), the code can be simplified even further (by removing the dealloc override completely).

@interface ClassA: NSObject
@property (nonatomic, copy) NSString* stringA;
@end

@implementation ClassA
@end

In this case stringA is released by your class on dealloc, but you don't have to write code to do that; ARC does it for you.

zpasternack
  • 17,838
  • 2
  • 63
  • 81
  • You do need to do it if you don't use ARC. Sometimes you might do manual synthesis if you need control over the ivar name. – uchuugaka Aug 16 '14 at 21:19