Where is the DEBUG macro defined? - objective-c

When I run code such as the following:
- (void)viewDidLoad
{
#ifdef DEBUG
NSLog(#"debug");
#else
NSLog(#"here");
#endif
[super viewDidLoad];
}
I see "debug" printed in the log, but I did not define DEBUG explicitly. Where is it defined?

It is most likely defined in your Build Settings under Preprocessor Macros.
Here is an example from one of my projects

Related

Create and access "debugMode" variable across different classes

I am trying to create a Boolean variable, debugMode, and access it across several different classes. This way I can set it's value once in my ViewController, and will be able to access it in my different classes (subclasses of SKScene) to show framerate, log physics values, etc.
I have read that I need to create an instance of my class? I don't see how that applies in this program.
I am new to objective-c and would greatly appreciate any help! Thank you!
The default solution is a preprocessor define, this is set by default in xcode projects.
So, in the source you can put
#ifdef DEBUG
// code that should only run in Debug Configuration
#endif
So if I get you right you want an instance of a given class that you can use across the whole of your application without losing the state of the class but this should only exist in the DEBUG version of your code?
Ok we can do this using a Singleton Pattern mixed with the #ifdef DEBUG to determine whether in debug mode or not.
DebugManager.h
// Our Debug Class that we have just made up.
// Singleton class
#interface DebugManager : NSObject
// Some properties that we want on the class
#property (nonatomic, strong) NSString *debugName;
#property (nonatomic, readonly) NSDate *instanceCreatedOn;
// a method for us to get the shared instance of our class
+ (id)sharedDebugManager;
#end
DebugManager.m
#import "DebugManager.h"
#implementation DebugManager
// Create a shared instance of our class unless one exists already
+ (id)sharedDebugManager
{
static DebugManager *sharedDebugManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedDebugManager = [[self alloc] init];
});
return sharedDebugManager;
}
- (id)init
{
if (self = [super init]) {
debugName = #"Debug Instance";
instanceCreatedOn = [NSDate new];
}
return self;
}
#end
Now that we have a Singleton class setup we can add the below line to our *-Prefix.pch which will give us an instance of our DebugManager class that we can use throughout our app.
#ifdef DEBUG
DebugManager *manager = [DebugManager sharedDebugManager];
#endif
Just remember that when you want to use your manager instance you will need to wrap it in #ifdef DEBUG because when running in production this will not see the instance of manager anymore. So make sure you do:
#ifdef DEBUG
NSLog(#"The DebugManagers instance name is %#", [manager debugName]);
#endif
Don't forget to add your preprocessor macro in xcode under your Build Settings follow this answer to find out how to do that
If you have any questions just ask below.

C preprocessor directive to conditionally compile method calls with square brackets

I know I can use preprocessor macros to conditionally compile certain method calls, for example:
#if SOMETHING
#define fmod(...)
#endif
...
fmod(34.0, 452.0); //this line doesn't get compiled if SOMETHING != 0.
Can I use the same procedure to conditionally compile method calls with opening and closing brackets?
Say I'd like to conditionally compile all calls to the class MyClass:
[MyClass doSomething];
[MyClass doSomethingElse];
#define MyClass[...] produces:
[ doSomething];
And that's an error. Any thoughts?
This is a workaround rely on fact that calling method on nil is no operation
#interface MyClassImpl : NSObject
+ (void)doSomething;
#end
#if SOMETHING
#define MyClass MyClassImpl
#else
#define MyClass ((Class)Nil)
#endif
You won't have any luck overloading the square brackets with macros, but you can flesh out your macro to have the effect you want with different syntax. Conditionally define a macro that takes an argument. In one case, the macro will resolve to just the argument, in the other case, the macro will resolve to white space.
(Edited to use variadic macro)
#define COMPILE_CONDITIONAL
#if defined(COMPILE_CONDITIONAL)
#define conditional(...) __VA_ARGS__
#else
#define conditional(...)
#endif
Then your use cases would look like:
conditional(fmod(34.0, 452.0));
conditional(MyClass doSomething);
conditional(MyClass doSomethingElse);
You will probably end up using a shorter macro than "conditional" typing that on every line gets old fast.

Generate gcda-files with Xcode5, iOS7 simulator and XCTest

Being inspired by the solution to this question I tried using the same approach with XCTest.
I've set 'Generate Test Coverage Files=YES' and 'Instrument Program Flow=YES'.
XCode still doesn't produce any gcda files. Anyone have any ideas of how to solve this?
Code:
#import <XCTest/XCTestLog.h>
#interface VATestObserver : XCTestLog
#end
static id mainSuite = nil;
#implementation VATestObserver
+ (void)initialize {
[[NSUserDefaults standardUserDefaults] setValue:#"VATestObserver"
forKey:XCTestObserverClassKey];
[super initialize];
}
- (void)testSuiteDidStart:(XCTestRun *)testRun {
[super testSuiteDidStart:testRun];
XCTestSuiteRun *suite = [[XCTestSuiteRun alloc] init];
[suite addTestRun:testRun];
if (mainSuite == nil) {
mainSuite = suite;
}
}
- (void)testSuiteDidStop:(XCTestRun *)testRun {
[super testSuiteDidStop:testRun];
XCTestSuiteRun *suite = [[XCTestSuiteRun alloc] init];
[suite addTestRun:testRun];
if (mainSuite == suite) {
UIApplication* application = [UIApplication sharedApplication];
[application.delegate applicationWillTerminate:application];
}
}
#end
In AppDelegate.m I have:
extern void __gcov_flush(void);
- (void)applicationWillTerminate:(UIApplication *)application {
__gcov_flush();
}
EDIT: I edited the question to reflect the current status (without the red herrings).
EDIT To make it work I had to add the all the files under test to the test target including VATestObserver.
AppDelegate.m
#ifdef DEBUG
+ (void)initialize {
if([self class] == [AppDelegate class]) {
[[NSUserDefaults standardUserDefaults] setValue:#"VATestObserver"
forKey:#"XCTestObserverClass"];
}
}
#endif
VATestObserver.m
#import <XCTest/XCTestLog.h>
#import <XCTest/XCTestSuiteRun.h>
#import <XCTest/XCTest.h>
// Workaround for XCode 5 bug where __gcov_flush is not called properly when Test Coverage flags are set
#interface VATestObserver : XCTestLog
#end
#ifdef DEBUG
extern void __gcov_flush(void);
#endif
static NSUInteger sTestCounter = 0;
static id mainSuite = nil;
#implementation VATestObserver
+ (void)initialize {
[[NSUserDefaults standardUserDefaults] setValue:#"VATestObserver"
forKey:XCTestObserverClassKey];
[super initialize];
}
- (void)testSuiteDidStart:(XCTestRun *)testRun {
[super testSuiteDidStart:testRun];
XCTestSuiteRun *suite = [[XCTestSuiteRun alloc] init];
[suite addTestRun:testRun];
sTestCounter++;
if (mainSuite == nil) {
mainSuite = suite;
}
}
- (void)testSuiteDidStop:(XCTestRun *)testRun {
sTestCounter--;
[super testSuiteDidStop:testRun];
XCTestSuiteRun *suite = [[XCTestSuiteRun alloc] init];
[suite addTestRun:testRun];
if (sTestCounter == 0) {
__gcov_flush();
}
}
Update 1:
After reading a bit more about this, 2 things have now become clear to me (emphasis added):
Tests and the tested application are compiled separately. Tests are actually injected into the running application, so the __gcov_flush() must be called inside the application not inside the tests.
— Xcode5 Code Coverage (from cmd-line for CI builds) - Stack Overflow
and,
Again: Injection is complex. Your take away should be: Don’t add .m files from your app to your test target. You’ll get unexpected behavior.
— Testing View Controllers – #1 – Lighter View Controllers
The code below was changed to reflect these two insights…
Update 2:
Added information on how to make this work for static libraries, as requested by #MdaG in the comments. The main changes for libraries is that:
We can flush directly from the -stopObserving method because there isn't a separate app where to inject the tests.
We must register the observer in the +load method because by the time the +initialize is called (when the class is first accessed from the test suite) it's already too late for XCTest to pick it up.
Solution
The other answers here have helped me immensely in setting up code coverage in my project. While exploring them, I believe I've managed to simplify the code for the fix quite a bit.
Considering either one of:
ExampleApp.xcodeproj created from scratch as an "Empty Application"
ExampleLibrary.xcodeproj created as an independent "Cocoa Touch Static Library"
These were the steps I took to enable Code Coverage generation in Xcode 5:
Create the GcovTestObserver.m file with the following code, inside the ExampleAppTests group:
#import <XCTest/XCTestObserver.h>
#interface GcovTestObserver : XCTestObserver
#end
#implementation GcovTestObserver
- (void)stopObserving
{
[super stopObserving];
UIApplication* application = [UIApplication sharedApplication];
[application.delegate applicationWillTerminate:application];
}
#end
When doing a library, since there is no app to call, the flush can be invoked directly from the observer. In that case, add the file to the ExampleLibraryTests group with this code instead:
#import <XCTest/XCTestObserver.h>
#interface GcovTestObserver : XCTestObserver
#end
#implementation GcovTestObserver
- (void)stopObserving
{
[super stopObserving];
extern void __gcov_flush(void);
__gcov_flush();
}
#end
To register the test observer class, add the following code to the #implementation section of either one of:
ExampleAppDelegate.m file, inside the ExampleApp group
ExampleLibrary.m file, inside the ExampleLibrary group
#ifdef DEBUG
+ (void)load {
[[NSUserDefaults standardUserDefaults] setValue:#"XCTestLog,GcovTestObserver"
forKey:#"XCTestObserverClass"];
}
#endif
Previously, this answer suggested to use the +initialize method (and you can still do that in case of Apps) but it doesn't work for libraries…
In the case of a library, the +initialize will probably be executed only when the tests invoke the library code for the first time, and by then it's already too late to register the observer. Using the +load method, the observer registration in always done in time, regardless of which scenario.
In the case of Apps, add the following code to the #implementation section of the ExampleAppDelegate.m file, inside the ExampleApp group, to flush the coverage files on exiting the app:
- (void)applicationWillTerminate:(UIApplication *)application
{
#ifdef DEBUG
extern void __gcov_flush(void);
__gcov_flush();
#endif
}
Enable Generate Test Coverage Files and Instrument Program Flow by setting them to YES in the project build settings (for both the "Example" and "Example Tests" targets).
To do this in an easy and consistent way, I've added a Debug.xcconfig file associated with the project's "Debug" configuration, with the following declarations:
GCC_GENERATE_TEST_COVERAGE_FILES = YES
GCC_INSTRUMENT_PROGRAM_FLOW_ARCS = YES
Make sure all the project's .m files are also included in the "Compile Sources" build phase of the "Example Tests" target. Don't do this: app code belongs to the app target, test code belongs to the test target!
After running the tests for your project, you'l be able to find the generated coverage files for the Example.xcodeproj in here:
cd ~/Library/Developer/Xcode/DerivedData/
find ./Example-* -name *.gcda
Notes
Step 1
The method declaration inside XCTestObserver.h indicates:
/*! Sent immediately after running tests to inform the observer that it's time
to stop observing test progress. Subclasses can override this method, but
they must invoke super's implementation. */
- (void) stopObserving;
Step 2
2.a)
By creating and registering a separate XCTestObserver subclass, we avoid having to interfere directly with the default XCTestLog class.
The constant key declaration inside XCTestObserver.h suggests just that:
/*! Setting the XCTestObserverClass user default to the name of a subclass of
XCTestObserver indicates that XCTest should use that subclass for reporting
test results rather than the default, XCTestLog. You can specify multiple
subclasses of XCTestObserver by specifying a comma between each one, for
example #"XCTestLog,FooObserver". */
XCT_EXPORT NSString * const XCTestObserverClassKey;
2.b)
Even though it's common practice to use if(self == [ExampleAppDelegate class]) around the code inside +initialize [Note: it's now using +load], I find it easier to omit it in this particular case: no need to adjust to the correct class name when doing copy & paste.
Also, the protection against running the code twice isn't really necessary here: this is not included in the release builds, and even if we subclass ExampleAppDelegate there is no problem in running this code more than one.
2.c)
In the case of libraries, the first hint of the problem came from this code comment in the Google Toolbox for Mac project: GTMCodeCovereageApp.m
+ (void)load {
// Using defines and strings so that we don't have to link in XCTest here.
// Must set defaults here. If we set them in XCTest we are too late
// for the observer registration.
// (...)
And as the NSObject Class Reference indicates:
initialize — Initializes the class before it receives its first message
load — Invoked whenever a class or category is added to the Objective-C runtime
The “EmptyLibrary” project
In case someone tries to replicate this process by creating their own "EmptyLibrary" project, please bear in mind that you need to invoke the library code from the default emtpy tests somehow.
If the main library class is not invoked from the tests, the compiler will try to be smart and it won't add it to the runtime (since it's not being called anywhere), so the +load method doesn't get called.
You can simply invoke some harmless method (as Apple suggests in their Coding Guidelines for Cocoa # Class Initialization). For example:
- (void)testExample
{
[ExampleLibrary self];
}
Because you have to create a new XCTestSuiteRun instance in the testSuiteDidStop method, you are not going to get the proper results on an == check. Instead of depending on instance equality, we used a simple counter and call flush when it hits zero, which it will when the top-level XCTestSuite finishes executing. There are probably more clever ways to do this.
First, we had to set 'Generate Test Coverage Files=YES' and 'Instrument Program Flow=YES' in both the Test and main app targets.
#import <XCTest/XCTestLog.h>
#import <XCTest/XCTestSuiteRun.h>
#import <XCTest/XCTest.h>
// Workaround for XCode 5 bug where __gcov_flush is not called properly when Test Coverage flags are set
#interface GCovrTestObserver : XCTestLog
#end
#ifdef DEBUG
extern void __gcov_flush(void);
#endif
static NSUInteger sTestCounter = 0;
static id mainSuite = nil;
#implementation GCovrTestObserver
- (void)testSuiteDidStart:(XCTestRun *)testRun {
[super testSuiteDidStart:testRun];
XCTestSuiteRun *suite = [[XCTestSuiteRun alloc] init];
[suite addTestRun:testRun];
sTestCounter++;
if (mainSuite == nil) {
mainSuite = suite;
}
}
- (void)testSuiteDidStop:(XCTestRun *)testRun {
sTestCounter--;
[super testSuiteDidStop:testRun];
XCTestSuiteRun *suite = [[XCTestSuiteRun alloc] init];
[suite addTestRun:testRun];
if (sTestCounter == 0) {
__gcov_flush();
}
}
#end
There was an additional step required, because the +initialize call was not being made on the observer when included in the Test target.
In the AppDelegate, add the following:
#ifdef DEBUG
+(void) initialize {
if([self class] == [AppDelegate class]) {
[[NSUserDefaults standardUserDefaults] setValue:#"GCovrTestObserver"
forKey:#"XCTestObserverClass"];
}
}
#endif
Here's another solution that avoids having to edit your AppDelegate
UIApplication+Instrumented.m (put this in your main target):
#implementation UIApplication (Instrumented)
#ifdef DEBUG
+ (void)load
{
NSString* key = #"XCTestObserverClass";
NSString* observers = [[NSUserDefaults standardUserDefaults] stringForKey:key];
observers = [NSString stringWithFormat:#"%#,%#", observers, #"XCTCoverageFlusher"];
[[NSUserDefaults standardUserDefaults] setValue:observers forKey:key];
}
- (void)xtc_gcov_flush
{
extern void __gcov_flush(void);
__gcov_flush();
}
#endif
#end
XCTCoverageFlusher.m (put this in your test target):
#interface XCTCoverageFlusher : XCTestObserver
#end
#implementation XCTCoverageFlusher
- (void) stopObserving
{
[super stopObserving];
UIApplication* application = [UIApplication sharedApplication];
SEL coverageFlusher = #selector(xtc_gcov_flush);
if ([application respondsToSelector:coverageFlusher])
{
objc_msgSend(application, coverageFlusher);
}
[application.delegate applicationWillTerminate:application];
}
#end
- (void)applicationWillTerminate:(UIApplication*)application must be defined in your application delegate, not in the observer class.
I didn't have any library problems. "-lgov" is not needed and you don't have to add any libraries. Coverage is supported directly by LLVM compiler.
The process for this is a little different if you're using Specta, since it does its own swizzling. The following is working for me:
Test Bundle:
#interface MyReporter : SPTNestedReporter // keeps the default reporter style
#end
#implementation MyReporter
- (void) stopObserving
{
[super stopObserving];
UIApplication* application = [UIApplication sharedApplication];
[application.delegate applicationWillTerminate:application];
}
#end
AppDelegate:
- (void)applicationWillTerminate:(UIApplication *)application
{
#ifdef DEBUG
extern void __gcov_flush(void);
__gcov_flush();
#endif
}
You then need to enable your custom reporter subclass by setting the environmental variable SPECTA_REPORTER_CLASS to MyReporter in the Run section of your main scheme.
GCOV Flush in -(void)applicationWillTerminate didn't work for me, I think because my App is running in Background.
I also set 'Generate Test Coverage Files=YES' and 'Instrument Program Flow=YES' but no gcda-Files.
Then I executed "__gcov_flush()" in -(void)tearDown from the TestClass, which gave me gcda-Files for my TestClass ;)
Then I created the following Function in my AppDelegate:
#interface AppDelegate : UIResponder <UIApplicationDelegate>
+(void)gcovFlush;
#end
#implementation AppDelegate
+(void)gcovFlush{
extern void __gcov_flush(void);
__gcov_flush();
NSLog(#"%s - GCOV FLUSH!", __PRETTY_FUNCTION__);
}
#end
I called [AppDelegate gcovFlush] in my -(void)tearDown and voilá, there are my gcda Files ;)
I hope this helps, bye Chris

Can't get MonoTouch binding library to work

I can't even get the simplest kind of binding library to work - I must be doing something fundamentally wrong...
I created an Xcode project called “TestLib” that looks like this:
// TestLib.h
#import <Foundation/Foundation.h>
#interface TestLib : NSObject
{
NSString *status;
}
#property (nonatomic,retain) NSString *status;
#end
// TestLib.m
#import "TestLib.h"
#implementation TestLib
#synthesize status;
- (id)init
{
self = [super init];
if (self) {
[self setStatus:#"initialized"];
}
return self;
}
#end
The project is here: http://dl.dropbox.com/u/31924320/TestLib.tar.gz
I compiled this into “libTestLib.a”.
Then I created the simplest binding library I could (along with a “single view application” to test it), which simply initializes the TestLib class and calls the getter for the status property. I added the library (libTestLib.a) into the binding library so it has the LinkWith file / assembly directive. The ApiDefinition.cs file looks like this:
namespace TestLibBinder
{
[BaseType(typeof(NSObject))]
interface TestLib
{
[Export("status")]
string Status { get; set; }
}
}
That project is here: http://dl.dropbox.com/u/31924320/BindingTest.tar.gz
Unfortunately I get a null reference back from the library when I try to get the Status property…
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
TestLib testLib = new TestLib(); // succeeds!
string status = testLib.Status; // got a null reference
if (status != null)
label.Text = status;
else
label.Text = "binding failed";
}
I got this to work by stepping away from the Binding Library project approach and instead basing my code on the BindingSample in the xamarin sample suite.
Anyone who wants to build a C# binding to objective-C code using MonoTouch should really start by reviewing the Makefile in that project. The approach it outlines is:
Explicitly compile the Objective-C code for the three architectures (ARM6, ARM7, i386)
Use lipo to create a single universal static library
Use btouch to create the DLL and include the static library through the assembly directive (LinkWith) - see AssemblyInfo.cs in that
project - as well as in the btouch commandline through the --link-with
option.
I personally found the process of creating the ApiDefinition.cs wrapper to be fairly straightforward, but there are some common mistakes - e.g. forgetting the trailing colon on a selector that takes one parameter.

Subclassing UIWindow - Need Preprocessor Help

Yes, I know subclassing UIWindow is frowned upon, but my subclassed UIWindow is for debugging purposes only (it takes a screenshot of the current-page once a specific motion event is detected).
Anyway, I made a custom precompiler flag called DEBUG in my project's Build Settings, but I'm having a problem getting it to load/function properly. Right now, it's not taking the screenshot, but it is registering the occurrence of the motion event.
Here's the code I have in the AppDelegate's didFinishLaunchingWithOptions:
#if DEBUG
DebugWindow *debugWindow = [[DebugWindow alloc] init];
self.window = debugWindow; //'window' is declared in the AppDelegate's #interface file and synthesized as window=_window in the #implementation file
#else
self.window = _window;
#endif
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
Here is how to use debug flag
#if DEBUG == 1
#define CMLog(format, ...) NSLog(#"%s:%#", __PRETTY_FUNCTION__,[NSString stringWithFormat:format, ## __VA_ARGS__]);
#define MARK CMLog(#"%s", __PRETTY_FUNCTION__);
#define START_TIMER NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
#define END_TIMER(msg) NSTimeInterval stop = [NSDate timeIntervalSinceReferenceDate]; CMLog([NSString stringWithFormat:#"%# Time = %f", msg, stop-start]);
#else
#define CMLog(format, ...)
#define MARK
#define START_TIMER
#define END_TIMER(msg)
#endif
And here is the screenshot
Also in the release setting put the flag to 0
Like this -DDEBUG=0
This way you can achieve what you want to achieve.Let me know if it helps or not.