Saturday, August 23, 2014

[English] Useful Macros

1. [NSString stringWithFormat:]

#define STRFORMAT(f, ...) [NSString stringWithFormat:f, __VA_ARGS__]

NSString* message = [NSString stringWithFormat:@"HELLO %3.1d", 333.333];

-> NSString* message = STRFORMAT(@"HELLO %3.1d", 333.333);

2. NSLocalizedString

#define LSTR(s) NSLocalizedString((s), nil)

NSString* message = NSLocalizedString(@"KEY", nil);

-> NSString* message = LSTR(@"KEY");

3. Class Method

#define ME [self class]

[ExampleClass classMethod];

-> [ME classMethod];

4. Block's __weak self

#define PREPARE_SELF __weak typeof(self) SELF = self

__weak MyClass* SELF = self;
[self doSomethingWithBlock:^{
    [SELF showAlert];
}];

->
PREPARE_SELF;
[self doSomethingWithBlock:^{
    [SELF showAlert];
}];

5. Hex Color

#define HEXCOLOR(c) [UIColor colorWithRed:((c>>16)&0xFF)/255.0 green:((c>>8)&0xFF)/255.0 blue:(c&0xFF)/255.0 alpha:1.0]

HEXCOLOR(0x34ff78);

6. 4 inch Size Check


#define IS_IPHONE4INCH (([[UIScreen mainScreen] bounds].size.height-568)?NO:YES)

if (IS_IPHONE4INCH) {
.....
}

7. iOS Version Major

#define IOS_VERSION_MAJOR [[[[[UIDevice currentDevice]systemVersion] componentsSeparatedByString:@"."] objectAtIndex:0] intValue]

if (IOS_VERSION_MAJOR < 7) {
....
}

8. Document Path

#define DOCUMENT_PATH [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]

9. NSLog
In release version you want to remove all NSLog, but when debug code's log is very usefully. This macro disable NSLog in release version and enable in debug.

#ifdef DEBUG
#  define LOG(...) NSLog(__VA_ARGS__)
#  define LOG_CURRENT_METHOD NSLog(@"%@/%@", NSStringFromClass([self class]), NSStringFromSelector(_cmd))
#else
#  define LOG(...) ;
#  define LOG_CURRENT_METHOD ;
#endif

NSLog(@"Test");

-> LOG(@"Test");

10. Async

#define TTAsync(...) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ##__VA_ARGS__)

11.  Async Main Queue

#define TTAsyncMain(...) dispatch_async(dispatch_get_main_queue(), ##__VA_ARGS__)

12. Dispatch Once

#define TTOnce(...) { \
    static dispatch_once_t __wb_oncePred; \
    dispatch_once(&__wb_oncePred, ##__VA_ARGS__); \
}

No comments:

Post a Comment