Rak*_*esh 5 string format methods cocoa objective-c
我不知道如何提出这个问题.我想创建一个类似stringWithFormat:or 的方法predicateWithFormat:,即我的方法直接接受参数作为带有格式说明符的字符串.我怎样才能做到这一点?
例如,
-(void) someMethod: (NSString *)str, format;
Run Code Online (Sandbox Code Playgroud)
所以我以后可以称之为:
[someObject someMethod:@"String with format %@",anotherString];
Run Code Online (Sandbox Code Playgroud)
这与任何特定背景无关.
我正在predicateWithFormat使用类似于的代码:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like myName"];
Run Code Online (Sandbox Code Playgroud)
这不起作用,但是:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like 'myName'"];
Run Code Online (Sandbox Code Playgroud)
工作类似于:
NSString *str = @"myName";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@",str];
Run Code Online (Sandbox Code Playgroud)
所以这意味着该方法能够理解给定的参数是否具有在其中使用的格式说明符.我很好奇怎么能这样做?
tro*_*foe 11
使用可变参数宏va_start,va_end等:
-(void) someMethod: (NSString *)fmt, ...
{
va_list va;
va_start(va, fmt);
NSString *string = [[NSString alloc] initWithFormat:fmt
arguments:va];
va_end(va);
// Do thing with string
}
Run Code Online (Sandbox Code Playgroud)
要记住的重要一点是,vararg参数会丢失它们的类型,因此函数printf()和[NSString stringWithFormat]使用格式字符串来帮助确定有多少参数以及如何解释每个参数.如果您需要不同的语义,那么您需要提供一些信息.
您正在寻找参数数量可变的方法。方法需要这样声明:
-(void) someMethod: (NSString *)str, ...; // Yes, three dots
Run Code Online (Sandbox Code Playgroud)
在该方法内部,您可以使用宏一一提取参数。第一个参数需要提供足够的信息以告诉您传递了多少个其他参数。例如,stringWithFormat通过计数未转义的%格式说明符可以知道传递了多少参数。
- (void) someMethod:NSString *)str, ... {
va_list args;
va_start(args, str);
int some_count = /* figure out how many args there are */;
for( int i = 0; i < some_count; i++ ) {
value = va_arg(args, <some_type>); // You need to derive the type from the format as well
}
va_end(args);
}
Run Code Online (Sandbox Code Playgroud)