开发者

Objective-c setter/getter callback

I have an interface with proper开发者_如何学Goties.

I would like to know the way to declare callback to reach its instance's setter or getter. Is there a way to do it?

Sorry for my english and thx for your answers and time.


If you declared a @property for your instance variable, and then synthesized it in your implementation file, your getter and setter are automatically created for you. Example for a NSMutableArray

@interface ... 
{  
   NSMutableArray *array;
}

@property (nonatomic, retain) NSMutableArray *array;

Then on your implementation:

@implementation ...
@synthesize array;

Once that's done, you can get and set your instance variable values by using:

Getter: self.array OR [self array]

Setter: self.array = ... OR [self setArray:...]


I am not sure if I understand your question correctly but if you are trying to get some code executed every time the setter or getter is invoked there are basically two ways to do that:

1) you can overwrite the synthesized getter and/or setter like this

Header:

@interface ...
{
   NSString *example;
}
@property (nonatomic, copy) NSString *example;

Implementation:

@implementation ...
@synthesize aString

-(void)setExample:(NSString *)newExample
{
   if (example != newExample)
   {
      [example autorelease];
      example = [newExample copy];

      // YOUR CODE HERE
   }
}

...and similarly for the getter.

2) you can observe the variable via KVO and get a 'callback' whenever the variable changes. This, of course, only runs you code when the setter is invoked, not the getter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜