Reputation: 126337
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?
Upvotes: 5
Views: 8526
Reputation: 86651
I think the issue ids that your getter and setter names are not consistent. By default, if you have
foo.immediate
in your code, it is assumed that the getter and setter are named -immediate
and -setImmediate:
respectively. Your getter is not named correctly. The best way around this is to declare a property as Mark and Kenny have already said but you could also change the name of your getter.
The point is that you do not need declared properties to use dot syntax, but if you are going to use dot syntax then declared properties are the recommended way of declaring the getter and setter.
Upvotes: 3
Reputation: 16938
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.
Upvotes: 10
Reputation: 523304
Declare such property in the @interface:
@interface PasscodeLock : NSObject {
}
@property(dynamic, getter=isImmediate,
setter=setImmediate:) BOOL immediate;
// etc.
@end
(The setter=
part is optional)
Upvotes: 8