Using macros in Objective-C to register function name and line number

I have the following simplified code example:

// in .h file
// define a macro for partial method
#define debugWithMsg context:(CFStringRef)__FUNCTION__ lineNumber:__LINE__ debug:

@interface MyLogger : NSObject {
  ...
}

- (void) context:(CFStringRef)function 
      lineNumber:(int)line 
           debug:(NSString*)messageFormat, ...;
@end

I use this method in other classes to print debugging messages in the Xcode console. Here is an example. I am testing my debugging method (in the MyViewController class with a table view):

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
  ...
  // myLogger is an instance of MyLogger.
  [myLogger debugWithMsg@"something for %@", @"testing!"];
  ...
}
...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  ...
  [myLogger debugWithMsg@"something for %@", @"another testing!"];
  ...
}

; C/++ ObjC. , , , "" . : __FUNCTION__ ++, __LINE__ C. , . , XCode :

[timestamp] -[MyViewController tableView:numberOfRowsInSection:] line:107 - something for testing!
...
[timestamp] -[MyViewController tableView:cellForRowAtIndexPath:] line:124 - something for another testing!

MyLogger . ? - ?

, NSLog (fmt,...), :

MyDebugLog(instance, fmt, ....)

- MyLogger, fmt,... - var. :

#define MyDebugLog(logger, fmt, ...) \
  [logger, context:(CFStringRef)__FUNCTION__ lineNumber:__LINE__ \
   debug:fmt, ## _VA_ARGS__]

, "" " , :

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
  ...
  // myLogger is an instance of MyLogger.
  MyDebugLog(myLogger, @"something for %@", @"testing!"); // compiling error!
  ...
}

, . - ?

+3
1

, .

#define SFLog(message, ...) NSLog((@"SFLOG: %s [Line %d] " message), __PRETTY_FUNCTION__, __LINE__, ## __VA_ARGS__)

SFLog(@"Some var %f", myFloat);, , "SFLog" ( "SFError" ) __PRETTY_FUNCTION__.


[EDIT]

SO, . .


[]

, ##. ## GCC- C99. ## LLVM/Clang 1.5 (XCode 3.2.4), -std = c99 -std = gnu99. , , .

+5

Source: https://habr.com/ru/post/1781600/


All Articles