views:

53

answers:

3

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 format string 2) an huge, dynamically created "list" of arguments"

that would be cool.

+1  A: 

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);
progrmr
**`[NSMutableString`** `stringWithFormat:`...
KennyTM
yeah, I saw that too, fixed.
progrmr
+1  A: 

Your underlying problem shouldn't be a problem. Just use +predicateWithFormat:argumentArray:. What issue are you having building this up?

Rob Napier
Hey Rob, that was exactly the right thing I needed. Perfect!
dontWatchMyProfile
Glad it helped. If you're doing complex build-up you may also want to consider building the actual predicate by hand and skipping the format string altogether. I use this technique when I'm converting simple search grammars into predicates. If your predicates really are large, this can also be faster since you skip the string parsing. See "Creating Predicates Directly in Code" here: http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/Predicates/Articles/pCreating.html
Rob Napier
+1  A: 

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];
ohhorob