dynamic string format with NSString stringWithFormat

后端 未结 3 1624
一向
一向 2021-02-04 14:37

I\'ve been trying to make a dynamic string format so that through user options precision or padding could be somewhat user defined.

An example includes, the padding of

3条回答
  •  青春惊慌失措
    2021-02-04 15:13

    Use two steps:

        NSString* hourString=nil;
        if(...){
             hourString=[NSString stringWithFormat:@"%i", hour];
        }else{
             hourString=[NSString stringWithFormat:@"%02i", hour];
        }
        NSString* result=[NSString stringWithFormat:@"Hour: %@", hourString];
    

    The following is considered a bad practice:

        NSString* formatString=nil;
        if(...){
             formatString=@"Hour: %i";
        }else{
             formatString=@"Hour: %02i";
        }
        NSString* result=[NSString stringWithFormat:formatString, hour];
    

    because it's very dangerous to have a variable formatString, which can be used in many types of cracker attacks.

提交回复
热议问题