在head first iphone development中看到关于属性的readwirte和retain有如下解释,
readwrite:When you want the property to be modifiable by people. The compiler will
generate a getter and a setter for you. This is the defaultretain:When you’re dealing with object values. The compiler will retain the value
you pass in and release the
old value when a new one comes in.请问readwrite自动生成的代码中,setter方法的实现是retain新的对象并release旧的对象吗?我觉得默认的readwrite属性应该符合内存管理的要求。

解决方案 »

  1.   

    setter方法的实现是retain新的对象release是创建的新对象!
      

  2.   

    不用理解得太复杂了。
    retain可以简单的理解引用计数加一,你现在要用就retain,用完得releasesetter只是简单的赋值,没那么复杂的。不可能读写一次属性就会分配再释放一段内存。创建这个属性的时候这段内存已经分配好了,来新的就retain,旧的就释放了(系统做的)。
      

  3.   

    官方:// retain 
    -(void)setMyObject:(id)newValue{
        if (_myObject != newValue) { 
            [_myObject release]; 
            _myObject = [newValue retain]; 
        }  
    }
      

  4.   

    定义set方法的时候,先release旧的,再给它赋新的。
      

  5.   

    对的,@synthesize生成的访问器是符合内存管理的,不需要你去关心引用计数问题。
    当你在你的析构函数里或者其他位置: self.yourObject = nil; 时yourObject的内存就会自动被释放
      

  6.   

    不建议使用readwrite,这样不利于内存管理,虽然使用Retain需要手动释放内存,但是这样可以合理的管理内存,是用完后立即释放。
      

  7.   

    一个很重要的理由让你使用retain,你用set的话你的属性值不知道什么时候就给删了。
      

  8.   

    readwrite:When you want the property to be modifiable by people. The compiler will
    generate a getter and a setter for you. This is the default
    这个不要管,除非你只指定readretain:When you’re dealing with object values. The compiler will retain the value
    you pass in and release the
    old value when a new one comes in
    这个关键字也是不要管的,作用就是保证你在用这个对象是不会释放,内存管理不需要你动手
      

  9.   

    re ad wr i te 
    表明了属性是可读写的。这是默认的参数 
    表示属性具有获取器和设置器一对访问器方法 
    re ado n l y 
    表明了属性是只读的,且只有获取器方法 
    如果试图对属性使用点语法赋值,将引发编译 
    错误