سؤال

I need to, for example, execute NSLog(@"Executed.") every time my synthesized getter or setter gets called. I see 2 ways to do that:

  1. Find some snippets that work probably like synthesized ones. This thread may help in that.
  2. Use KVO: add some observer which will do the work.

All of them doesn't looks satisfactory clean for me. So, subj.

UPDAE: Thank for answers, but directly overriding isn't a solution: we loose synthesized code. If we "copy paste" "right" synthesized code from somewhere (even from apple forum where apple engineer gives us code) we should check that it isn't changed after next compiler release.

هل كانت مفيدة؟

المحلول

You can write an additional property, with your custom getter and setter, that does your own thing, and then accesses the @synthesized ones, like so:

Foo.h:

@interface Foo : NSObject
{
    int bar;
}

@property int bar;
@property int bar2;


@end

Foo.m:

#import "Foo.h"

@implementation Foo

@synthesize bar;

- (int) bar2
{
    NSLog(@"getter");
    return self.bar;
}

- (void) setBar2:(int)newBar
{
    NSLog(@"setter");
    self.bar = newBar;
}
@end

and then your code:

Foo *foo = [[Foo alloc] init];
foo.bar2 = 1;
foo.bar2 += 2;
[foo release];

So you would use "bar2" as your property, but you get all the niceties out of the @synthesized bar. Anything in bar would be set/get in a thread safe manner, and any additional logic in bar2 would not (which may not matter to you)

نصائح أخرى

I would recommend you to add an observer to the synthesized property since it would be the most clean solution.

If you are not satisfied with this way you may just want to override the getter/setter?

So in your interface:

@property (nonatomic, strong) NSString *testString;

And in your implementation:

@synthesize testString; //this is used to generate a setter/getter if we don't override one of them

-(NSString *)testString {
    NSLog(@"Executed.");
    return testString;
}

-(void)setTestString:(NSString *)newValue {
    NSLog(@"Executed.");
    if (testString != newValue){
        [newValue retain];
        [testString release];
        testString = newValue;
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top