0

I would like to verify something that I always use but when I think about it ... I get confused why it worked that way and I sure I read the explanation about it but I cant find it. As far as I understand apple create their setter as something like this.

-(void)setString:(NSString *)value {
   if (_string != value) {
      [_string release];
      _string = [value retain];
   }
}

Now usually I create properties like this.

@property (nonatomic) NSString *string;
@synthesize string = _string;

The question is about next code:

        NSString *s = @"Should be deleted";
        [self setString:s];
        NSLog(@"string check111 =%@",self.string);
        s = NULL;
        NSLog(@"string check222=%@",self.string);

The same output will be generated. From the setter I can see that my property points on the object that I changed but the property value will be the same.That situation triggers another question (if it works like that why would I need copy attribute). Can someone provide a short explanation about it? (or concrete link to read). Tnx A Lot. (I think my question may be already asked in the forum )

Mike.R
  • 2,824
  • 2
  • 26
  • 34
  • You assertion that "string 's' should be deleted" is wrong in the first place. Just setting a reference to NULL has nothing to do with deallocation of the object it points. – erkanyildiz Jun 14 '14 at 19:52
  • You are all right,if I had a chance I would delete that stupid question. – Mike.R Jun 14 '14 at 20:48

2 Answers2

4

This has no effect because you are changing the object to which s points to.

This diagram probably explains it better, originally you have something like this:

enter image description here

Changing the point of s will not affect _string.

enter image description here

The idea of setting the property to copy is in case you set your string property to a mutable string and then change the content of it. See this question.

Community
  • 1
  • 1
lucianomarisi
  • 1,552
  • 11
  • 24
  • Yes, you totally right I don't what I was thinking about when posting that kind of question. – Mike.R Jun 14 '14 at 20:36
1

I guess it would be something like this

    NSString *s = @"Should be deleted"; // create autoreleased string
    [self setString:s]; // retain string
    NSLog(@"string check111 =%@",self.string);
    s = NULL; // reset pointer value to null. This operation doesn't affect string object
    NSLog(@"string check222=%@",self.string);
    // string's retain counter will be decreased by autorelease pool later
Ivan Fateev
  • 1,032
  • 1
  • 10
  • 26