2013-10-04 98 views
0

我有这个协议。如何在objective-c中设置协议属性的默认值?

//MyProtocolClass.h 
@protocol MyProtocolDelegate <NSObject> 

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

@end 

@interface MyProtocolClass:NSObject 
@end 

然后我使用这个类此协议:

//.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 

我想设置一个默认值100上的可变anInteger使得它保持该值阉用户设置,或不。

的NSLogs应该输出:

100 
200 

我知道如何用一个函数来做到这一点,但我可以做到这一点使用属性? 谢谢。

+0

你只能在类方法中设置anInteger = 100',协议不能实现方法 – pNre

+0

所以对于这样的属性可以没有默认值(开箱即用)..对吗? – SudoPlz

+0

是的,你是对的 – pNre

回答

1

属性仅仅是一个对方法,吸气和一个setter。而已。它没有提到吸气和吸气装置如何实施。没有理由认为有一个支持“价值”。

0

设置属性值,

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

并调用这样,

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

我在哪里打电话给这个?我的意思是,我不想在MyClass.m上调用它,我更喜欢默认值是在MyProtocolClass.m上给出的 – SudoPlz