Using #define to access application delegation object does not work

I am using the App Delegate object in different classes. I want to access it in the whole project. Define this object in the Prefix.pch file as

#define Appdelegate (AppDelegate *)[[UIApplication sharedApplication] delegate] 

but the problem is that the Appdelegate variable does not have access to the application delegation variable. it indicates an error.

but if i use this code works fine

 AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; appDelegate.variablename; 

Am I doing it right or is there a way to do what I'm doing?

Thanks at Advance.

+7
source share
3 answers

Must be:

 #define Appdelegate ((AppDelegate *)[[UIApplication sharedApplication] delegate]) // ^----------------------parenthesis--------------------------^ 
+15
source

You need to import the AppDelegate file, where you declare the delegate macro:

import "AppDelegate.h"

And then define

define Appdelegate (((AppDelegate *) [[UIApplication sharedApplication] delegate]))

+2
source

As this question and its answers show, relying on a preprocessor is usually a bad idea.

  • It's easy to make a mistake. We all develop good instincts for operator precedence, but the preprocessor has no idea. To guard against unforeseen context issues, you often need to wrap everything in extra parsers and curly braces.

  • It’s easy to convince yourself that you are doing one thing when the code is doing the other. When everything breaks, neither the compiler error messages nor the debugger will most likely help.

  • Most importantly, the preprocessor can allow you to accept a bad idea and spread it everywhere through the program. The bad idea here is to use an application delegate around the world.

Global variables are the smell of code. The effort to make global variables even more global by typing them into precompiled headers is the smell of code. If, within the framework of the structure, you should have access to AppDelegate from all sides, you will not need to jump over these (modest) hoops!

So, when it is tempting to do something like this, it's nice to know that there is a preprocessor, and there are pch headers, but keep in mind that you are fighting with a wireframe and almost certainly make a design mistake. It may be good in your context, but it is something to know.

+1
source

All Articles