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?
Property access functions are only called when using the
x.pnotation. You can access the instance variable backing the property with justp(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:However, you needn’t use
@dynamichere.@synthesizeis smart, and will only create defaults if you’ve not provided them. So feel free to justWhich will create the getter, but not the setter in this case.