objective-cobjective-c-2.0google-style-guide

Is count a property or not?


In the official google style guide for objective c, it's mentioned that

Dot notation is idiomatic style for Objective-C 2.0. It may be used when doing simple operations to get and set a @property of an object, but should not be used to invoke other object behavior.

The following is the preferred way of getting/setting properties as opposed to using brackets:

NSString *oldName = myObject.name;
myObject.name = @"Alice";

The following is the non-preferred way of doing the same:

NSArray *array = [[NSArray arrayWithObject:@"hello"] retain];
NSUInteger numberOfItems = array.count;  // not a property
array.release;                           // not a property

However, according to the style guide, count is not a property and hence should use the bracket notation. However, count really is a property. Can anyone weigh in on this please?


Solution

  • If you refer to the documentation for NSArray, you'll see count is definitely a property

    https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/#//apple_ref/occ/instp/NSArray/count

    It sounds like the style guide just had a mistake. As you said dot notation is preferred for property accessors-- but even more so with getters. array.count is correct.

    However it does make sense that mistake was made because in other languages, count is not normally stored as a property, and you would need to call a method to retrieve the count. NSArray is special :)