oc的内存管理

@implementation Dog

(void)dealloc
{
  NSLog(@"Dog 被销毁了");
  [super dealloc];
}

@end
@class Dog;
@interface Person : NSObject

@property(retain) Dog *dog;

@end

int main(int argc, const char * argv[]) {
  Person *p1 = [[Person alloc] init];
  Person *p2 = [[Person alloc] init];
  Dog *d = [[Dog alloc] init];

  p1.dog = d;
  p2.dog = d;
  [d release];

  p1.dog = nil;
  p2.dog = nil;
  return 0;
}//Dog *d被销毁了

int main(int argc, const char * argv[]) {
  Person *p1 = [[Person alloc] init];
  Person *p2 = [[Person alloc] init];
  Dog *d = [[Dog alloc] init];

  p1.dog = d;
  p2.dog = p1.dog;  // 只改了这一行
  [d release];

  p1.dog = nil;
  p2.dog = nil;
  return 0;
}//Dog *d没有被销毁

dog属性声明为了atomic类型,为了保证原子性,dog的set和get方法应该做过处理。我感觉mrc下的atomic属性的set和get方法应该如下

- (Dog *) dog {
    Dog *d = nil;
     @synchronized(self) {
        d = [[_dog retain] autorelease];
    }
     return d;
}

- (void)setDog:(Dog *)dog {
    @synchronized(self) {
        [dog retain];
        [_dog release];
        _dog = dog;
    }
}

所以在调用p2.dog = p1.dog;的时候会先调用p1.dog的get方法,内部会对dog retain一次,引用计数+1,然后放进自动释放池,再调用p2.dog的set方法,又会retain一次。最后release的时候-1,引用计数最后仍然是1,所以不会被释放

你可能感兴趣的:(oc的内存管理)