Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a property without instance variable?

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?

like image 437
tomidelucca Avatar asked Feb 27 '12 03:02

tomidelucca


People also ask

Which type of properties can be referenced without creating an instance of the class?

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.

What's the difference between instance variable and property?

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.

Are instance variables properties?

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.


1 Answers

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.

like image 160
Lily Ballard Avatar answered Nov 16 '22 00:11

Lily Ballard