function

In the following function which one is the best practice?

  • To send an autoreleased object, and make the caller retain it?

  • or send an allocated object, and make the caller release it?


  • - (NSString*) convertDataToString :(NSData*)myData
    {
         //just an example, method might not exist
         NSString *str = [[NSString alloc] initWithData:myData];
         return str;
         return [str autoRelease];
    }
    

    The memory management rules say your first example is — and this is a direct quote — wrong. It's not even a matter of preference, as some answers here seem to indicate. The caller does not normally own the object you return, so it should be autoreleased.

    The specific example from the rules says this:

    This is wrong. Following the ownership policy, it would result in a memory leak.

     – (NSArray *)sprockets {
    
        NSArray *array = [[NSArray alloc] initWithObjects:mainSprocket,
                                   auxiliarySprocket, nil];
        return array;
    }
    

    The object's reference to the new array object is limited to the sprockets method. After the method returns, the object loses its reference to the new object so cannot relinquish ownership. That in itself is not a problem. However, following the naming convention set out earlier, the caller is given no indication that it owns the returned object. The caller would therefore not relinquish ownership of the returned object, leading to a memory leak.


    Following up on @Chuck's comment, -convertDataToString must not return an object that the caller must release. That would violate the Three Magic Words. If you do not have "copy," "alloc," or "new" in your name, the caller cannot be expected to release the object. If you have "copy" in your name or start with "new" or "alloc," then the caller must release the object.

    Objective-C relies heavily on consistent naming and the names mean things. If you learn the naming, then you won't have any problems.


    You'd want to return an autoreleased object most of the time . Unless your method name contains one of the following words [alloc, new, copy], you should return an autoreleased object.

    链接地址: http://www.djcxy.com/p/43730.html

    上一篇: 核心数据会产生分析器警告

    下一篇: 功能