如果我想将这些属性用作dinnerPrefMethod 方法的参数,该怎么做。[...] 我的目标是能够调用该方法,并将对象的两个属性作为参数。
听起来您想避免这样做:
FamilyMember *familyMember = [[FamilyMember alloc] init];
[familyMember setName:@"First Last"];
[familyMember setPreference:dunno];
[familyMember announceDinnerPreference];
-[FamilyMember announceDinnerPreference]
您的修改版本在哪里dinnerPrefMethod:
:
- (void)announceDinnerPreference
{
NSLog(@"Let's see what %@ wants for dinner...", [self name]);
switch ([self preference]) {
case pizza:
NSLog(@"%@ wants pizza.", [self name]);
break;
case steak:
NSLog(@"%@ wants steak.", [self name]);
break;
case seafood:
NSLog(@"%@ wants seafood.", [self name]);
break;
case dunno:
NSLog(@"%@ doesn't know.", [self name]);
break;
}
}
也许你想定义一个方法-[FamilyMember setName:preference:announceDinnerPreference:]
- (void)setName:(NSString *)name preference:(dinnerPreference)preference announceDinnerPreference:(BOOL)announce
{
[self setName:name];
[self setPreference:preference];
if (announce) {
[self announceDinnerPreference];
}
}
这将允许你写
FamilyMember *familyMember = [[FamilyMember alloc] init];
[familyMember setName:@"First Last" preference:dunno announceDinnerPreference:YES];
不过,坦率地说,这在风格上非常奇怪。
一种更时尚的方法是定义-initWithName:preference:
- (id)initWithName:(NSString *)name preference:(dinnerPreference)preference
{
self = [super init];
if (self) {
[self setName:name];
[self setPreference:preference];
}
return self;
}
然后你就可以写了
FamilyMember *familyMember = [[FamilyMember alloc] initWithName:@"First Last" preference:dunno];
[familyMember announceDinnerPreference];
所以我可以在方法中使用对象的属性而不说它们是参数吗?
是的。对象的实例变量可以在其实例方法中访问。