How to dynamically build up the arguments for NSLog?
Example: I have a complex method that does a lot of stuff, and at the end I want to print a report with NSLog. NSLog wants a string, and then an arbitrary number of arguments. So lets say there are these possible values which can be logged:
A
B
C
D
E
F
It can happen that -for example- C and D are not logged, but the whole rest. How would I build up a dynamic thing which represent the value arguments for NSLog?
I choose NSLog for this question because it may be simpler aus NSPredicate and SUBQUERY. It seems impossible to build an NSPredicate format string dynamically while using an NSMutableString and appendFormat:... it results always in compile errors for the predicate. I guess that NSPredicate does something different with it's provided format values than NSMutableString -appendFormat does.
So if there was a way to feed NSPredicate with: 1) a huge, dynamically created for开发者_如何学Cmat string 2) an huge, dynamically created "list" of arguments"
that would be cool.
Something like this should do it, conditionally append parts to the string:
NSMutableString* logMsg = [NSMutableString stringWithFormat:@"%@ %@ %@", A, B, C];
if (C) [logMsg appendFormat:@" %@", C];
if (D) [logMsg appendFormat:@" %@", D];
[logMsg appendFormat:@" %@ %@", E, F];
NSLog(@"%@", logMsg);
Your underlying problem shouldn't be a problem. Just use +predicateWithFormat:argumentArray:
. What issue are you having building this up?
If you're collecting a variable list of strings to be output at one time, simply use a NSMutableArray
adding a line of log output as needed. Then at the end of the process, joing the components with a string:
NSMutableArray *logLines = [[NSMutable alloc] initWithCapacity:10];
...
NSLog(@"Multiple-line output:\n%@",[logLines componentsJoinedByString:@"\n"]);
[logLines release];
精彩评论