2

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?

4

1 回答 1

2

如果您参考文档NSArray,您会看到 count 绝对是一个属性

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

听起来风格指南只是有一个错误。正如您所说,点表示法对于属性访问器来说是首选——但对于 getter 来说更是如此。 array.count是正确的。

然而,犯错是有道理的,因为在其他语言中,count 通常不存储为属性,您需要调用方法来检索计数。 NSArray很特别:)

于 2015-04-09T05:07:02.397 回答