C pointer array not recognized in Swift - objective-c

I'm converting/importing some legacy code into Swift and I have to use a file of constants that look like this:
Constants.h
extern const int workingConstant;
extern int constantArray1[];
extern int constantArray2[];
extern int constantArray3[];
extern int *problematicConstant[];
Constants.m
const int workingConstant = 3;
int constantArray1 [] = {2,50,50,49,47,46,44,42,16,41,49,47,46,44,42,41,16,64,64,62,62,60,60};
int constantArray2 [] = {72,718,63,740,94,756,117,755,127,759,121,767,120,777,118,788};
int constantArray3 [] = {226,505,226,505,213,518,206,531,230,545,250,562,258,575,265,560,277,543};
int* problematicConstant [] = {constantArray1,constantArray2,constantArray3}
In my legacy Objective C code I can import the header and call a method like:
-(void)doStuff:(int)firstConstant paths:(int **)paths shrink_p:(CGAffineTransform *)shrink_p{
CGMutablePathRef hitPath = CGPathCreateMutable();
for(int i = 0; i < firstConstant; i++){
CGPathMoveToPoint(hitPath, &(*shrink_p), paths[firstConstant][i+1]);
}
}
that takes the workingConstant and the problematicConstant and is a method of a subview. My .swift UIView subclass successfully finds the workingConstant however the problematicConstant is throwing a "Use of unresolved identifier" error when I try to call doStuff on my subview.

I was able to reproduce your problem with some mock-up code. For whatever reason Swift can't see problematicConstant via the bridging header. However, I was able to circumvent this by adding yet another global variable:
extern int ** ppInt; // in the header
int ** ppInt = problematicConstant; // in the Objective-C implementation
The extern declaration and definition can go into the existing Objective-C source or, if you want to keep it clean, into separate header and implementation files. In fact, the extern can just be in the bridging header.
As an aside, the constantArray... declarations could not be bridged, either, but if you need them, you can do a similar trick:
int * pInt1 = constantArray1;
...

Related

String substitution with variable constants [duplicate]

This question already has answers here:
Objective C Macro append to string
(3 answers)
Closed 6 years ago.
In my project, I define my urls like such:
#define TERMSURL #"http://127.0.0.1:8000/terms/"
#define PRIVACYURL #"http://127.0.0.1:8000/privacy/"
...
Since the root url (http://127.0.0.1:8000/) is always the same, is there a way to set it as a constant, and then use string substitution for the remaining pieces?
For example, in the other files, I could do something like this:
NSString *devBaseUrl = #"http://127.0.0.1:8000/";
NSString *url1 = [NSString stringWithFormat:#"%#terms/", devBaseUrl];
Is there a way to do that for my current approach?
shared.h
#define TERMSURL #"http://127.0.0.1:8000/terms/"
#define PRIVACYURL #"http://127.0.0.1:8000/privacy/"
#define URL_BASE #"http://127.0.0.1:8000/"
yourClass.m
NSString * stringUrlBase = URL_BASE;
NSString *url1 = [NSString stringWithFormat:#"%#terms/", stringUrlBase];
Sure, you can do that. I have however seen both a #define and an NSString const * const being used before. Defines are easier, and you're probably not going to save that much memory by having constants instead of individual immutable instances of NSString all over the place.
Some advice is to think about how you export the NSString constants. You'll probably want EXTERN_PRIVATE instead of EXTERN, but my sample code will allow all clients of your header to read the string constants you've declared therein.
What you can do:
Create a new .m/.c file with a header in Xcode
In the .m/.c file, declare and initialise your constants
Export the constant as necessary so other compilation units can access it
constants.h
#ifndef constants_h
#define constants_h
// Export the symbol to clients of the static object (library)
#define EXTERN extern __attribute__((visibility("default")))
// Export the symbol, but make it available only within the static object
#define EXTERN_PRIVATE extern __attribute__((visibility("hidden")))
// Make the class symbol available to clients
#define EXTERN_CLASS __attribute__((visibility("default")))
// Hide the class symbol from clients
#define EXTERN_CLASS_PRIVATE __attribute__((visibility("hidden")))
#define INLINE static inline
#import <Foundation/Foundation.h>
EXTERN NSString const * _Nonnull const devBaseUrl;
#endif /* constants_h */
constants.m
#include "constants.h"
NSString const * _Nonnull const devBaseUrl = #"http://127.0.0.1:8000/";
main.m
#import <Foundation/Foundation.h>
#import "constants.h"
int main(int argc, const char * argv[]) {
#autoreleasepool {
NSLog(#"Constant value: %#", devBaseUrl);
// Prints: Constant value: http://127.0.0.1:8000/
}
return 0;
}

objective-c constants.h static const

I googled a lot of similar questions, but none of them had a really good answer about what i needed.
Im wondering about the best way to write constants in some .h file.
my constants file is just a clear file with no imports, just clear .h file. I import it in prefix file.
when i use
static NSInteger someInteger = 1;
or
static BOOl someBool = YES;
The compiler compiles okay but gives me a warning that this variable is unused even though im using it multiple times in different classes.
But if i use
static NSString* someString = #"";
there are not any warnings.
also if i use
const NSInteger someInteger = 1;
Compiler compiles okay for a real device, but when running on a simulator it does not compile with an error duplicate symbols for architecture i386
also what is the difference between
const NSString* someString = #"";
const NSInteger someInteger = 1;
and
NSString* const someString = #"";
NSInteger const someInteger = 1;
I ended up using static const NSInteger someInteger =1;, but i wonder if this is a right option.
So really my question is: what words should i use to successfully create a constants.h file?
For all types (both primitive or otherwise) then you need to provide a single implementation of it somewhere:
constants.h:
extern const int someValue;
extern NSString * const someString;
constants.m:
const NSInteger someValue = 1;
NSString * const someString = #"Some string";
You never want to use static variables in header files as you will end up with multiple copies of the "constant" in every implementation file that includes that header (they may not upset the linker, and cause a link error, but they are there).

Code in Objective C 2008 Does not compile

I'm learning the basics of objective-C by Reading 'Objective C For Dummies'.
I'm using XCode 4.4, and I'm trying to get some simple code to work. This question has been posed online before. However - the code doesn't seem to compile with the new version of XCode.
At issue seems to be the line NSLog (#"Here is some amazing text! %i",c); This throws an 'Expected Expression' Error. Per the previous form posting, I have disabled automatic reference checking in preferences and this still fails.
#include <stdio.h>
int main(int argc, const char * argv[])
{
//declare variables
int a;
int b;
int c;
//set the variables
a = 2;
b = 3;
//Perform the computations
c = a % b;
//Output the results
NSLog (#"Here is some amazing text! %c",c);
return 0;
}
Add #import <Foundation/Foundation.h> at the top, and change the NSLog to this:
NSLog (#"Here is some amazing text! %d",c);
Because %c doesn't mean "a variable called c", but rather a char. %d means an int, which is what c is.
You forgot to include the Foundation header:
#import <Foundation/Foundation.h>
Sidenote: The format specifier should be %d.

What is the best way to define string constants in an objective-c protocol?

I have defined a protocol that all my plug-ins must implement. I would also like the plug-ins to all use certain strings, like MyPluginErrorDomain. With integers this is quite easily achieved in an enum, but I can't figure out how to do the same with strings. Normally, in classes I would define
extern NSString * const MyPluginErrorDomain;
in the .h file and in the .m file:
NSString * const MyPluginErrorDomain = #"MyPluginErrorDomain";
but that doesn't work very well in a protocol, because then each plug-in would have to provide its own implementation which defeats the purpose of having a constant.
I then tried
#define MYPLUGIN_ERROR_DOMAIN #"MyPluginErrorDomain"
but the implementing classes in the plug-in can't seem to see the #define. Who knows a good solution?
You can declare them in the header with the protocol (but outside the protocol interface itself), then define them in an implementation file for the protocol (obviously it wouldn't have an #implementation section - just your NSString definitions).
Or have a separate .h/.m pair that is just for the string constants (the protocol header can import the string constants header).
You keep the .h definition:
extern NSString * const MyPluginErrorDomain;
but put this part into a separate .m file that gets included in your framework:
NSString * const MyPluginErrorDomain = #"MyPluginErrorDomain";
So plug-ins can still implement the interface but when compiling they link or compile in your other .m file, so they will see the value of MyPluginErrorDomain.
In C++, I would declare them in a header like this:
const char * const MYPLUGIN_ERROR_DOMAIN = "MyPluginErrorDomain";
const char * const MYPLUGIN_FOO_DOMAIN = "MyPluginFooDomain";
Note that as the pointers are const, they will be local to the translation units the header is #included in, and so there will be no need to use extern to prevent multiple definition errors.
You should implement it as extern strings as in your example:
extern NSString * const MyPluginErrorDomain;
or provide extern functions which return static storage data. For example:
/* h */
extern NSString * MyPluginErrorDomain();
/* m */
NSString * MyPluginErrorDomain() {
static NSString * const s = #"MyPluginErrorDomain";
return s;
}
The reason is that strings and keys are often used and compared by pointer value or hash value, rather than true string comparison (isEqualToString:).
At the implementation level, there is a big difference between:
In code, that means that when the strings compared are defined in multiple binaries:
Say 'MyPluginErrorDomain' and 'key' have identical string values, but are defined in different binaries (i.e. on in the plugin host, one in the plugin).
/////// Pointer comparison (NSString)
BOOL a = [MyPluginErrorDomain isEqualToString:key];
BOOL b = MyPluginErrorDomain == key;
// c may be false because a may be true, in that they represent the same character sequence, but do not point to the same object
BOOL c = a == b;
/////// Hash use (NSString)
// This is true
BOOL d = [MyPluginErrorDomain hash] == [key hash];
// This is indicative if true
BOOL e = [MyPluginErrorDomain hash] == [someOtherStringKey hash];
// because
BOOL f = [MyPluginErrorDomain isEqualToString:someOtherStringKey];
// g may be false (though the hash code is 'generally' correct)
BOOL g = e == f;
It is therefore necessary to provide the keys in many cases. It may seem like a trivial point, but it is hard to diagnose some of the problems associated with the difference.
Hash codes and pointer comparisons are used throughout Foundation and other objc technologies in the internals of dictionary storage, key value coding... If your dictionary is going straight out to xml, that's one thing, but runtime use is another and there are a few caveats in the implementation and runtime details.

Objective-C error: initializer element is not constant

Why does the compiler give me the following error message on the provided code: "initializer element is not constant". The corresponding C/C++ code compiles perfectly under gcc.
#import <Foundation/Foundation.h>
const float a = 1;
const float b = a + a; // <- error here
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// insert code here...
NSLog(#"Hello, World!");
[pool drain];
return 0;
}
That code will only compile correctly if the const float statements appear somewhere other than the file scope.
It is part of the standard, apparently. It is important that all file-scope declared variables are initialised with constant expressions, not expressions involving constant variables.
You are initialising the float 'b' with the value of another object. The value of any object, even if it is a const qualified, is not a constant expression in C.
#dreamlax is correct, you can't have a const declaration whose initialization depends upon another (const) variable. If you need one to depend on the other, I suggest creating a variable that you can treat as a constant and initialize it only once. See these SO questions for details:
Defining a constant in objective-c
Constants in Objective C
I don't have Xcode on my machine here so I can't try my example,
But can you try
#define A (1)
#define B (A + A)
const float a = A;
const float b = B;