SudoPlz
SudoPlz

Reputation: 23193

How do I set the default value of a protocol property in objective-c?

I'e got this protocol.

//MyProtocolClass.h
@protocol MyProtocolDelegate <NSObject>

@optional
@property (nonatomic, assign) int anInteger;

@end

@interface MyProtocolClass:NSObject
@end

Then I'm using this protocol on this class:

//.h
@interface MyClass:NSObject <MyProtocolDelegate>
@end

//.m
@implementation MyClass
@synthesize anInteger;

    -(void) aFunction
    {
        NSLog(@"%d",self.anInteger);
        self.anInteger = 200;
        NSLog(@"%d",self.anInteger);
    }

@end

I want to set a default the value 100 on the variable anInteger so that it holds that value wether the user sets it or not.

The NSLogs should output:

100
200

I know how to do this using a function but can I do this using a property? Thank you.

Upvotes: 2

Views: 792

Answers (2)

newacct
newacct

Reputation: 122429

A property is just a pair of methods, a getter and a setter. That's it. It says nothing about how the getter and setter may be implemented. There is no reason to assume that there is a backing "value" at all.

Upvotes: 1

karthika
karthika

Reputation: 4091

set the property value,

-(void)setAnInteger:(int)anInteger
{
    self.anInteger = anInteger;
}

and call like this,

[self setAnInteger:100];
[self setAnInteger:200];

Upvotes: 0

Related Questions