I'm trying to add a property without creating an instance variable. Is it possible to do this? Or can you do something similar in a way that's not a property?
Example:
@interface RandomClass()
@property (nonatomic) int value;
@end
@implementation RandomClass
@synthesize value = _value;
// Here I override the default methods @synthesize
-(int)value
{
return 8; // Actually I'm returning something more complex, so a "define" won't work
}
-(void)setValue:(int)value
{
self.someOtherValue = value;
}
In the code above, I'm not using the instance variable _value
! Is there a way to do this without creating the variable?
A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created.
A property can be backed by an instance variable, but you can also define the getter/setter to do something a bit more dynamic, e.g. you might define a lowerCase property on a string which dynamically creates the result rather than returning the value of some member variable.
Each instance variable lives in memory for the lifetime of the object it is owned by. Variables are properties an object knows about itself. All instances of an object have their own copies of instance variables, even if the value is the same from one object to another.
Remove the line
@synthesize value = _value;
Since you're implementing the getter/setter yourself, the @synthesize
isn't helpful.
@synthesize
serves two jobs. The first job is to connect the property to a backing ivar, synthesizing the ivar if it doesn't already exist. The second job is to synthesize the getter/setter. If you don't need the backing ivar, and if you're providing implementations for the getter/setter yourself, then you don't need the @synthesize
at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With