3

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]) { ...
ikevin8me
  • 4,253
  • 5
  • 44
  • 84

3 Answers3

12

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;
Community
  • 1
  • 1
Rob
  • 415,655
  • 72
  • 787
  • 1,044
10

You can use KeyValue coding.

just send name of a property as NSString

- (void) method:(NSString*)propertyName
{
  [self setValue:[NSNumber numberWithInt:2] forKey:propertyName];
}

also a property is just to methods (set and get), so you can pass a selector

SEL selector = @selector(setProperty:);

- (void) method:(SEL)selector target:(id)target
{
  [target performSelector:selector withObject:[NSNumber numberWithInt:2]];
}

i prefer to use key value coding.

Remizorrr
  • 2,322
  • 1
  • 17
  • 25
  • Your approach is preferable since the first class can log in the setter when it's getting set and to what value. In @Rob s solution the original class never knows if that variable is getting changed behind its back. – David H Oct 07 '12 at 13:43
  • Both appear to be much better answers than the others here. – ArtOfWarfare May 02 '13 at 16:26
2
aProperty

is already a pointer to the NSDate object, so you just pass the pointer value along for 'call by reference'.

As the item is declared as a pointer, you can pass the reference using,

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

where the prototype for aMethod is...

- (BOOL) aMethod:(NSDate *) aParameter;

(the above is true unless you really do want to pass a pointer to the property itself - to modify the pointer to the property itself, in which case I would question your design)

Snips
  • 6,575
  • 7
  • 40
  • 64
  • 1
    This is not really what/where the problem is. I still agree with you on OP's design being fundamentally flawed, but the problem is that he wants another method to modify a variable, which is missing one level of indirection in your answer. –  Oct 06 '12 at 16:19