如果我想用這些屬性作爲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];
所以我可以使用屬性該方法中的對象沒有說他們是pa rameters?
是的。對象的實例變量可在其實例方法中訪問。
所以我可以在方法中使用對象的屬性,而不必說它們是參數? – ChrisHeneghan
是的,只有在實例方法(指該方法屬於同一類) –
謝謝,但是當我這樣做,我就當我宣佈說,switch語句行的錯誤「語句需要整數類型的表達式('dinnerPreference 「無效) – ChrisHeneghan