(readonly, copy) properties

Discussion in 'iOS Programming' started by seepel, Feb 28, 2011.

  1. seepel macrumors 6502

    seepel

    Joined:
    Dec 22, 2009
    #1
    Just a little confused on this point... If a property in a class I'm using has attributes (readonly, copy) (such as UIView's subviews property) does this mean I am being returned a copy of the object and I should release it? The documentation says that the copy is used in the assignment of the variable, but if it is readonly then it would never be set through the property so why declare the copy attribute at all?
     
  2. idelovski macrumors regular

    Joined:
    Sep 11, 2008
    #2
    You seem to be right. This line is from UIView.h:

    @property(nonatomic,readonly,copy) NSArray *subviews;

    But, this does not make any sense, really. Apple is describing copy as "Setter Semantics Attribute" so if something is readonly, copy attribute just does nothing.

    Maybe I am wrong, but this is what I wrote in one of my -viewDidLoad methods:

    Code:
       NSLog (@"Subviews: %p", self.view.subviews);
       NSLog (@"Subviews: %p", self.view.subviews);
       NSLog (@"Subviews: %p", self.view.subviews);
       NSLog (@"Subviews: %p", self.view.subviews);
    
    And in console, I had this:

    Subviews: 0x5f108b0
    Subviews: 0x5f108b0
    Subviews: 0x5f108b0
    Subviews: 0x5f108b0


    Same object, definitely.
     
  3. admanimal macrumors 68040

    Joined:
    Apr 22, 2005
    #3
    It has to do with re-declaring properties in subclasses or categories. So what is going on here is that in the private UIView class/header that Apple uses, subviews is declared as (readwrite, copy). However, the subviews property is exposed to us in the UIViewHierarchy category of UIView, which re-declares the property as (readonly, copy). The copy part of the property is required because it was part of the original property declaration, even though it is not relevant to a readonly property.
     
  4. huskerchad macrumors regular

    Joined:
    Jul 17, 2002
    #4
    Declaring a property as copy means that the setter will make a copy rather than retaining the provided argument. It has no effect on whether you should release something you obtain through an accessor.

    Either the copy or retain will eventually require a balancing release according to the standard memory management rules, but neither is your responsibility if you were not he one who did the copy or retain.
     
  5. seepel thread starter macrumors 6502

    seepel

    Joined:
    Dec 22, 2009
    #5
    Bingo! Thanks for the very clear description, makes me feel foolish for not knowing/figuring that one out.
     
  6. admanimal macrumors 68040

    Joined:
    Apr 22, 2005
    #6
    Don't feel foolish...I had no idea either and had to do some research to find the answer :)
     

Share This Page