Help on Objective-C BOOL methods [duplicate]
Possible Duplicate:
Help on Objective-C BOOL methods?
@interface
BOOL isCarryingmallet;
@implementation
-(BOOL)isCarryingWeapon {
return isCarryingMallet;
}
-(int)getWeaponDamage {
if (isCarryingMallet)
return kVikingMalletDamage;
else
return kVikingFistDamage;
}
I know that the -(BOOL)isCarryingWeapon
returns 开发者_JS百科isCarryingWeapon
, but I don't know why that's useful. Can someone give me an example of it?
Also, what does continue;
do in an if statement?
Thanks you!
Well -(BOOL)isCarryingWeapon
actually returns a bool. The type a method returns is whats specified in the brackets. e.g. (void)
is nothing (NSString)
would be a string.
-(BOOL)isCarryingWeapon {
return isCarryingMallet;
}
actually returns the value of isCarryingMallet. So calling [myObject isCarryingWeapon]
would give you a YES or NO based on the value of isCarryingMallet
.
Continue is used in loops for example
for (item in items)
{
if(item == NULL)
continue;
else
break;
}
continue means continue the loop on the next item from the start of the loop. break means stop looping. So you could use these in searching loops. If the item is not what you want you can continue to loop, if you find the item you want you could break ending the looping cycle early.
It's useful to access the isCarryingMallet
property from another class. You could also use accessor methods like this to make the property independent of an actual BOOL
variable, for example, if you later decide that you want to store the carried weapons in a list, you could still use the same method to determine whether that list is empty and wouldn't have to change any external code that relies on the method.
continue
doesn't do anything in an if
statement, except causing a compiler error if the if statement is not part of a loop. It continues the execution at the top of the loop at the top otherwise.
In an if
statement, continue
does not do anything. But if the if
is inside a loop (for
, or while
, or do
), then continue
jumps to the beginning of the loop body, like it always does.
but I don't know why that's useful
This is an example of data hiding, IMHO. The interface of the class has an isCarryingWeapon
method which the class consumers are welcome to call. If the class implementation is some day extended to allow for swords, you can change the content of [isCarryingWeapon] method to something like:
return isCarryingMallet || isCarryingSword;
and the callers won't know the difference.
精彩评论