Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: Custom BOOL accessor (getter & setter) methods

I know someone already asked about Writing getter and setter for BOOL variable. But, if I'm defining a custom getter & setter methods setImmediate & isImmediate, respectively, I'd like passcode.immediate = NO to work too.

I do not have any instance variables, but maybe I should? I could add one for NSDate *lastUnlocked.

Here's the relevant code so far:

// PasscodeLock.h

extern NSString *const kPasscodeLastUnlocked;

@interface PasscodeLock : NSObject {

}

- (BOOL)isImmediate;
- (void)setImmediate:(BOOL)on;

- (NSDate *)lastUnlocked;
- (void)resetLastUnlocked;
- (void)setLastUnlocked:(NSDate *)lastUnlocked;

@end


// PasscodeLock.m

#import "PasscodeLock.h"

NSString *const kPasscodeLastUnlocked    = @"kPasscodeLastUnlocked";

@implementation PasscodeLock

#pragma mark PasscodeLock

- (BOOL)isImmediate {
    return self.lastUnlocked == nil;
}

- (void)setImmediate:(BOOL)on {
    if (on) {
        [self resetLastUnlocked];
    } else {
        self.lastUnlocked = nil;        
    }
}

- (NSDate *)lastUnlocked {
    return [[NSUserDefaults standardUserDefaults] objectForKey:kPasscodeLastUnlocked];
}

- (void)resetLastUnlocked {
    NSDate *now = [[NSDate alloc] init];
    self.lastUnlocked = now;
    [now release];
}

- (void)setLastUnlocked:(NSDate *)lastUnlocked {
    [[NSUserDefaults standardUserDefaults] setObject:lastUnlocked forKey:kPasscodeLastUnlocked];
}

Then, in a view controller that has PasswordLock *passwordLock as an instance variable, I want to do passcode.immediate = NO, but I get the error "Property 'immediate' not found on object of type 'PasscodeLock *'."

How do I get passcode.immediate = NO to work?

like image 812
ma11hew28 Avatar asked Nov 30 '22 08:11

ma11hew28


1 Answers

You need something like

@property (nonatomic, getter=isImmediate) BOOL immediate;

in your .h file and of course a @synthesize statement in your .m file. This creates the property AND defines your getter method name.

like image 167
Mark Granoff Avatar answered Dec 04 '22 02:12

Mark Granoff