I want to create a method like this:
- (void) checkAndUpdateStringProperty: (NSString **) property{
if (...)
*property = @"whatever";
}
I want to use this to pass in a property for the same class:
- (void) somewhereElse{
....
[self checkAndUpdateStringProperty: &self.productName];
}
But this gives a syntax error, saying “Address of property expression requested”. Any reason why? If I replace the class property with a local variable, it works fine:
- (void) somewhereElse{
NSString *name = nil;
[self checkAndUpdateStringProperty: &name];
}
Properties should only ever be accessed through their getter and setter methods, with the exception of initializing and deinitializing them in the object’s
initanddeallocmethods (when the object is not in a fully consistent state) — accessing them any other way defeats their purpose and does not respect their attributes (retain,copy, etc.).The reason why it doesn’t compile is because property accessors are syntactic sugar for method calls, and you can’t take the address of the return value of a method.
self.productNameis identical to[self productName], and&[self productName]makes no sense.If you really want to do this, don’t do it with a property, do it with just a regular variable (such as a local variable or ivar), and document the semantics of your function: does the calling function need to
releasethe returned object? Etc. For example, the various Apple methods which take anNSError**specify that the error object which is returned, if any, is an autoreleased object, so you should notreleaseit yourself unless you alsoretainit.