macros FTW!
#define setString(X,Y) if(!X){X=[[NSMutableString alloc] initWithString:Y];}else{[X setString:Y];}
When I try to assign a value with this:
- It will always be initialized first
- It won't be initialized until I try to give it a value
- It doesn't clutter up my code
- It still gives a warning if X isn't an
NSMutableString
, or if Y isn't anNSString
orNSMutableString
- I haven't tested for if
Y
isnil
, but I expect it will cause a crash, which is what I want.
Drawbacks:
- I still have to remember to always use my
setString()
instead of the stocksetString:
- I'll have to do something similar for any other setters I call (the only one that I'm worried about off hand is
setValue:forKey:
, which I use extensively - one step at a time I guess) - a one size fits all solution would have been nice - maybe a topic for another question. Whatever I pass in has to be a
NSString
before I pass it, I cannot convert it to a string in line - but at least I get a build error if I try to do so, so it isn't up to me to remember to do so (still adds clutter though)NSMutableString *X;
int y = 0;
setString(X, [NSString stringWithFormat:@"%d",y]) // <--- Doesn't work
NSString *Y = [NSStirng stringWithFormat:@"%d",y];
setString(X,Y) // <--- Does work