Ios – Objective-C: Correct way to pass a property’s reference into a method call

cocoa, ios, macos, objective-c

If I have a property like this:

@property(strong, readwrite, nonatomic) NSDate* aProperty;

and I want to pass the reference into another method, are these correct:

if([AnotherClass aMethod:&(self.aProperty)]) { ...if([AnotherClass aMethod:&self.aProperty]) { ...

Best Solution

Considering your example:

if ([AnotherClass aMethod:&(self.aProperty)]) { ...

This obviously won't work because the dot notation is, effectively, using the getter accessor method. It's equivalent to:

if ([AnotherClass aMethod:&[self aProperty]]) { ...

You can easily imagine why the compiler is a little confused about this notation. The logical alternative would be to reference the ivar. Thus, (assuming you're using the underscore convention for the property's ivar) it might look like:

if ([AnotherClass aMethod:&_aProperty]) { ...

But that has all sorts of issues (bypassing setter, having issues about aMethod needing __strong attribute to override the default __autoreleasing as discussed here, etc.).

So, probably best, just have a local variable that receives the update, and then invoke the property's setter subsequent to that:

NSDate *date;if ([AnotherClass aMethod:&date]) { ...self.aProperty = date;