Reputation: 4313
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]) { ...
Upvotes: 3
Views: 7115
Reputation: 437402
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;
Upvotes: 12
Reputation: 2322
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.
Upvotes: 10
Reputation: 6753
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)
Upvotes: 2