Naming conventions for BOOL Obj-C 2 properties?

前端 未结 5 1406

I have a readonly BOOL property. What is dominant naming pattern here?

Background: for plain old method declarations, the accepted pattern

- (BOOL)is         


        
相关标签:
5条回答
  • 2020-12-14 17:47

    quoted from ADC

    If the attribute is expressed as an adjective, the format is:

    - (void)setAdjective:(BOOL)flag;
    - (BOOL)isAdjective;
    

    For example:

    - (void)setEditable:(BOOL)flag;
    - (BOOL)isEditable; 
    

    If the attribute is expressed as a verb, the format is:

    - (void)setVerbObject:(BOOL)flag; 
    - (BOOL)verbObject;
    

    For example:

    - (void)setShowsAlpha:(BOOL)flag;
    - (BOOL)showsAlpha; 
    

    The verb should be in the simple present tense.

    |K<

    0 讨论(0)
  • 2020-12-14 18:02

    You'd want to use the one that works with KVO, KVC and bindings etc.

    I remember reading that in the Docs that KVO et al. will look for is<key>, set<key> as well as get<key> and many others like countOf<key>

    The KVC Compliance Checklist explains it much better than I could ever do.

    0 讨论(0)
  • 2020-12-14 18:06

    I don't think it really matters, since KVO will look at both is<Key> and <Key>.

    Looking at the iPhone classes, the most common pattern I've seen is:

    @property(nonatomic, getter=isHidden) BOOL hidden;

    This let's you access the property in these ways:

    obj.hidden = YES; // (1)
    BOOL hidden = obj.hidden; // (2)
    BOOL hidden = [obj isHidden]; // (3)
    

    But not:

    BOOL hidden = obj.isHidden; // (4)
    

    CalStore does not follow that convention. You would be have to use line 4 instead of line 2.

    0 讨论(0)
  • 2020-12-14 18:06

    The convention is definitely to do is... for BOOL getters. The reason you see the property set like that in CalStore is most likely because it's read-only and written that way for basic readability of the header file, since:

    @property(readonly) isEditable;
    

    is generally easier to read than:

    @property(readonly, getter=isEditable) editable;
    

    For the first type of property, in your implementation you could do either of:

    @synthesize isEditable = editable;
    

    or simply define the accessor:

    - (BOOL)isEditable(void) { return editable; }
    

    This leaves the interface file (the header) more easily readable by a potential user.

    0 讨论(0)
  • 2020-12-14 18:11

    The CalStore example seems to be violating the convention. I'd stick to where the property name, as opposed to the method name, doesn't have an "is" in it.

    0 讨论(0)
提交回复
热议问题