今天讲自定义Accessor方法,除了前面讲的Objective-C会自动生成getter、setter的Accessor方法,你也可以自定义getter、setter方法。
You Can Implement Custom Accessor Methods
Properties don’t always have to be backed by their own instance variables.
As an example, the XYZPerson class might define a read-only property for a person’s full name:
@property (readonly) NSString *fullName;
Rather than having to update the fullName property every time the first or last name changed, it would be easier just to write a custom accessor method to build the full name string on request:
- (NSString *)fullName {
return [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName];
}
This simple example uses a format string and specifiers (as described in the previous chapter) to build a string containing a person’s first and last names separated by a space.
Note: Although this is a convenient example, it’s important to realize that it’s locale-specific, and is only suitable for use in countries that put a person’s given name before the family name.
If you need to write a custom accessor method for a property that does use an instance variable, you must access that instance variable directly from within the method. For example, it’s common to delay the initialization of a property until it’s first requested, using a “lazy accessor,” like this:
- (XYZObject *)someImportantObject {
if (!_someImportantObject) {
_someImportantObject = [[XYZObject alloc] init];
}
return _someImportantObject;
}
Before returning the value, this method first checks whether the _someImportantObject instance variable is nil; if it is, it allocates an object.
Note: The compiler will automatically synthesize an instance variable in all situations where it’s also synthesizing at least one accessor method. If you implement both a getter and a setter for a readwrite property, or a getter for a readonly property, the compiler will assume that you are taking control over the property implementation and won’t synthesize an instance variable automatically.
If you still need an instance variable, you’ll need to request that one be synthesized:
@synthesize property = _property;