Could someone please help me convert this into a global function? I will be using this code in multiple places, so it does not make sense to copy and paste it multiple times.
I'd like to be able to call <div class="navigation>
<a href="index.php" class="<?= underlinePage('index.php'); ?>">Home<a>
<a href="about.php" class="<?= underlinePage('about.php'); ?>">About me</a>
<a href="contact.php" class="<?= underlinePage('contact.php'); ?>">Contact me!</a>
</div>
and have it run through the function.
abbreviateNumber(number)
EDIT:
For example, I have a global function like this, but I do not know how to put the above in that type of format:
-(NSString *)abbreviateNumber:(int)num {
NSString *abbrevNum;
float number = (float)num;
if (num >= 1000) {
NSArray *abbrev = @[@"k", @"m", @"b"];
for (int i = abbrev.count - 1; i >= 0; i--) {
int size = pow(10,(i+1)*3);
if(size <= number) {
number = number/size;
NSString *numberString = [self floatToString:number];
abbrevNum = [NSString stringWithFormat:@"%@%@", numberString, [abbrev objectAtIndex:i]];
}
}
} else {
abbrevNum = [NSString stringWithFormat:@"%d", (int)number];
}
return abbrevNum;
}
- (NSString *) floatToString:(float) val {
NSString *ret = [NSString stringWithFormat:@"%.1f", val];
unichar c = [ret characterAtIndex:[ret length] - 1];
while (c == 48) {
ret = [ret substringToIndex:[ret length] - 1];
c = [ret characterAtIndex:[ret length] - 1];
if(c == 46) {
ret = [ret substringToIndex:[ret length] - 1];
}
}
return ret;
}
答案 0 :(得分:2)
You could add the two functions as categories on VTIMEZONE
, and call them from there:
NSString
in a @interface NSString(MyNSStringCategoryName)
+ (NSString *)stringByAbbreviatingNumber:(int)num;
+ (NSString *)stringFromFloat:(float)val;
@end
file, and
NSString+MyNSStringCategoryName.h
in a @implementation NSString(MyNSStringCategoryName)
+ (NSString *)stringByAbbreviatingNumber:(int)num {
// ... your code
}
+ (NSString *)stringFromFloat:(float)val {
// ... your code
}
@end
.
You can then call those class methods like this:
NSString+MyNSStringCategoryName.m
You gain modularization like this as you keep the string methods grouped together, while also having the benefit of having them globally available.
答案 1 :(得分:1)
Cristik's answer is good, but if you have a variety of tools you can make a class, for example, myGlobalTools and declare your methods as class methods. Change the - to a plus in the method declaration;
@ControllerAdvice
you can call them with;
+(NSString *)abbreviateNumber:(int)num;