Objective C: Accessing constants from other classes - iphone

I have a constant in one class that I want to access from another.
I want to access these:
#define kStateRunning 1
#define kStateGameOver 2
#define kStateMenu 3
which are in my GameController.h from Level1.m. In Level1.h I have #class GameController as well as an import in the implementation file.
I tried searching for an answer, but I'm not sure if I'm wording all this correctly.

If you use #define myConstant, myConstant will be known since you import your file. Define them at the beginning of your GameController.h between the import and the #Interface for example.
Then if you import GameController.h in one of your other files (let's take Level1.m for example). You can use it, without prefixing it. Just use myConstant

I wouldn't use #define as you lose any checking from the compiler. Generally you use a constant to avoid using magic values throughout your code that can be spelt wrong or typed wrong.
In the Apple docs for Coding Guidelines they tell you how you should approach each type of constant.
For simple integers like you have, they suggest enums are the best option. They are used extensively in the Apple frameworks so you know they are good.
You would still need to define it in your header.
e.g. (Use your own prefix instead of PS)
typedef enum {
PSGameStateRunning = 1,
PSGameStateGameOver,
PSGameStateMenu,
} PSGameState;
This also has the advantage of being a type that you can pass into/return from functions if you require

Related

Reflectively look up enum value by String in Swift 2

I'm writing an XML-based descriptor for UIKit and am wondering if there's any slim possibility at all of taking a string like "UIStackViewAlignmentCenter" or "UIStackViewAlignment.Center" and converting it into the appropriate constant value.
I'm really expecting this is impossible, but wanted to ask just in case.
My fallback plan is to create a helper class that allows me to register strings like "UIStackViewAlignmentCenter" and map them to values, but this is going to be painstaking adding all of the possible constants. :(

Using reflection to add properties

In Swift 2.1, I am trying to use reflection in order to add cases generated from a text file to an enum at compile time.
Here is the enum wrapper:
enum Kind : Int {
}
Using C/++ I could just use this macro:
#define X(value, left, right) \
value##Left = left, value##Right = right,
How can I get similar result in Swift?
Preprocessor directives are deliberately cut down to a very bare minimum in Swift. Even if technically possible, your particular case would go quite against Swift philosophy in respect of enums, as this philosopy requires that switch statements on enumerations are exhaustive, that is, cover all possible cases.
Now, if you would be able to dynamically fill up the enum's cases from some file, then how would compiler be able to ensure exhaustiveness? Opting out to use default: cases all over the program would basically throw the whole Swift's idea of enum safety right into the window.
If you stick with Swift then you are probably better off with dictionary as #RMenke suggests.

Swift replacement for Objective-C macro

I busy rewriting an app in Swift and would like to convert the following macro to Swift code.
#define FLOG(format, ...) NSLog(#"%#.%# %#", [self class], NSStringFromSelector(_cmd), [NSString stringWithFormat:format, ##__VA_ARGS__])
How can I define this as a Swift function such that I can use if anywhere for debug logging purposes, or is there an alternate way to achieve the same thing?
The easiest way is probably to take advantage of string interpolation and use:
func FLOG(message:String, method:String = __FUNCTION__) {
println("\(method): \(message)")
}
Then you usage is similar to:
FLOG("Illegal value: \(value)")
Having the method argument default to __FUNCTION__ means that it will normally be replaced with the calling function name. Other automatic variables that you could use include __FILE__, __LINE__ and __COLUMN__. Unfortunately __PRETTY_FUNCTION__ is no longer available.
If you want more control over the formatting of the message than string interpolation allows, take a look at this question which demonstrates simplifying access to printf-style formatting in Swift, and would let you do:
FLOG("Illegal value: %x" % [value])
See also this post from Apple that addresses using __FILE__ and __LINE__ in assert
Apple's answer to the removal of macros and something new to replace them is that nothing like macros will be available in swift. The closest you can get is to replace #define with a global let variable.
Example: instead of #define CONSTANT 0 you can write let CONSTANT = 0
Whereas, if you want to pass arguments inside a macro, that feature will no longer be available as considered bad programming practice. What you can do instead is create a function.

Why some variable of struct take preprocessor to function?

Variables of struct declared by data type of language in the header file. Usually data type using to declare variables, but other data type pass to preprocessors. When we should use to a data type send to preprocessor for declare variables? Why data type and variables send to processor?
#define DECLARE_REFERENCE(type, name) \
union { type name; int64_t name##_; }
typedef struct _STRING
{
int32_t flags;
int32_t length;
DECLARE_REFERENCE(char*, identifier);
DECLARE_REFERENCE(uint8_t*, string);
DECLARE_REFERENCE(uint8_t*, mask);
DECLARE_REFERENCE(MATCH*, matches_list_head);
DECLARE_REFERENCE(MATCH*, matches_list_tail);
REGEXP re;
} STRING;
Why this code is doing this for declarations? Because as the body of DECLARE_REFERENCE shows, when a type and name are passed to this macro it does more than just the declaration - it builds something else out of the name as well, for some other unknown purpose. If you only wanted to declare a variable, you wouldn't do this - it does something distinct from simply declaring one variable.
What it actually does? The unions that the macro declares provide a second name for accessing the same space as a different type. In this case you can get at the references themselves, or also at an unconverted integer representation of their bit pattern. Assuming that int64_t is the same size as a pointer on the target, anyway.
Using a macro for this potentially serves several purposes I can think of off the bat:
Saves keystrokes
Makes the code more readable - but only to people who already know what the macros mean
If the secondary way of getting at reference data is only used for debugging purposes, it can be disabled easily for a release build, generating compiler errors on any surviving debug code
It enforces the secondary status of the access path, hiding it from people who just want to see what's contained in the struct and its formal interface
Should you do this? No. This does more than just declare variables, it also does something else, and that other thing is clearly specific to the gory internals of the rest of the containing program. Without seeing the rest of the program we may never fully understand the rest of what it does.
When you need to do something specific to the internals of your program, you'll (hopefully) know when it's time to invent your own thing-like-this (most likely never); but don't copy others.
So the overall lesson here is to identify places where people aren't writing in straightforward C, but are coding to their particular application, and to separate those two, and not take quirks from a specific program as guidelines for the language as a whole.
Sometimes it is necessary to have a number of declarations which are guaranteed to have some relationship to each other. Some simple kinds of relationships such as constants that need to be numbered consecutively can be handled using enum declarations, but some applications require more complex relationships that the compiler can't handle directly. For example, one might wish to have a set of enum values and a set of string literals and ensure that they remain in sync with each other. If one declares something like:
#define GENERATE_STATE_ENUM_LIST \
ENUM_LIST_ITEM(STATE_DEFAULT, "Default") \
ENUM_LIST_ITEM(STATE_INIT, "Initializing") \
ENUM_LIST_ITEM(STATE_READY, "Ready") \
ENUM_LIST_ITEM(STATE_SLEEPING, "Sleeping") \
ENUM_LIST_ITEM(STATE_REQ_SYNC, "Starting synchronization") \
// This line should be left blank except for this comment
Then code can use the GENERATE_STATE_ENUM_LIST macro both to declare an enum type and a string array, and ensure that even if items are added or removed from the list each string will match up with its proper enum value. By contrast, if the array and enum declarations were separate, adding a new state to one but not the other could cause the values to get "out of sync".
I'm not sure what the purpose the macros in your particular case, but the pattern can sometimes be a reasonable one. The biggest 'question' is whether it's better to (ab)use the C preprocessor so as to allow such relationships to be expressed in valid-but-ugly C code, or whether it would be better to use some other tool to take a list of states and would generate the appropriate C code from that.

How to make a macro which gives back a string into the source code?

Example: I want to do this:
METHODNAME(5) {
// do something
}
which results in:
- (void)animationStep5 {
// do something
}
Is there any way to do this? Basically, what I need is a way to generate a real source code string before the program is compiled, so the compiler does see - (void)animationStep5...
Or maybe there's something different than a macro, which can help here to auto-generate method names (not at run-time)?
As was already answered here, the objective-C preprocessor is very close to the C one.
You should have a look at the examples posted there, and have a look at C proprocessor. You will simply have to use the ## syntax of the preprocessor, to concatenate the method name, and the number you want.
You can use the concatenation operator
#define METHODNAME(i) -(void)animationStep##i
you can call it like
METHODNAME(5){}
This expands to
-(void)animationStep5{}
Assuming the objective-c preprocessor behaves the same as the standard C one, you can use something like:
#define PASTE(a, b) a##b
#define METHODNAME(n) PASTE(animationStep,n)
to join the required bits together. This means that
METHODNAME(5)
gets translated to
animationStep5
(you may need to add the "void" from your question to the macro definitino depending on exactly what it is you need to do).