commscheck
commscheck

Reputation: 443

Creating Properties in Obj-C, how do I write the default Getter?

I'm just starting to learn Objective-C, one thing I'm trying to learn is good Property use. I'm currently trying to create some properties with custom setters. This is how far I've gotten:

@interface MyClass : NSObject
@property (nonatomic, assign) int myNumber;
@end

@implementation MyClass
@dynamic myNumber;

- (int)myNumber {
    return ???;
}

- (void)setMyNumber:newNumber {
    myNumber = newNumber;
    // custom stuff here
}

I really just want to implement a custom setter, I'm fine with the getter being default. However, how do I access the variable directly? If I put "return self.myNumber", won't that just call the getter method and infinite loop?

Upvotes: 1

Views: 189

Answers (2)

Adam Wright
Adam Wright

Reputation: 49376

Property access functions are only called when using the x.p notation. You can access the instance variable backing the property with just p (in Objective C, all members have the class instance variables in scope). You can, if you really want, also access via the pointer deference notation ->. So, any of these two:

return p;

return self->p;

However, you needn't use @dynamic here. @synthesize is smart, and will only create defaults if you've not provided them. So feel free to just

@synthesize p;

Which will create the getter, but not the setter in this case.

Upvotes: 1

user23743
user23743

Reputation:

- (int)myNumber {
    return myNumber;
}

Upvotes: 0

Related Questions