简体   繁体   中英

In NSString, is length an attribute or function?

As describe here:

length

str.length vs [str length]

is length attribute or method? Which one is correct implementation?

Is this standard iOS writing:

 if([self.clientNumberTxtField.text length] == 0)

length is a property. Therefore you can do:

NSInteger len = str.length;

But as you should know, a property is just glorified syntax for some appropriate combination of setter and getter methods and typically an instance variable. Since you get a "getter" method for this property, you can also do:

NSInteger len = [str length];

Both are perfectly valid. It's a matter of personal preference.

In Objective-C,property will create two default method for you.For example:

@property (nonatomic) NSUInteger length;
// then you will get two methods
- (NSUInteger)length;
- (void)setLength:(NSUInteger)length;

So you can call like this:

[str length];

As other commenters point out, length is a read-only property on NSString. Although the implementation is hidden from us I think we can safely assume that there is no variable backing it, it is computed from some other data member, (the characters in the string). Therefore I'd answer your question by saying it is more like a function than an attribute but this is academic, objective C gives us properties, which might perform computations or might simply return some underlying data member and you shouldn't worry about it, just use it :). Best

Ps myString.length is just shorthand for [myString length] , I'd take any wager you like that they compile to exactly the same thing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM