Objective C - Custom struct 'make' method similar to CLLocationCoordinate2DMake - ios

I've written a custom struct in a separate header file. It looks something like this
typedef struct RequestSpecifics {
BOOL includeMetaData;
BOOL includeVerboseData;
} RequestSpecifics;
Now I want to make a custom 'make' method, similar to the CoreLocation struct CLLocationCoordinate2 CLLocationCoordinate2DMake method.
I've tried two different ways. While both ways give no errors in the .h file, I do get errors when I want to use the make method.
Method 1:
extern RequestSpecifics RequestSpecificsMake(BOOL includeMetaData, BOOL includeVerboseData);
Throws:
Apple Mach-O Linker
"_RequestSpecificsMake", referenced from:
Error Linker command failed with exit code 1 (use -v to see invocation)
Method 2:
extern RequestSpecifics RequestSpecificsMake(BOOL includeMetaData, BOOL includeVerboseData) {
RequestSpecifics specifics;
specifics.includeMetaData = includeMetaData;
specifics.includeVerboseData = includeVerboseData;
return specifics;
}
Throws:
Apple Mach-O Linker
Error Linker command failed with exit code 1 (use -v to see invocation)
Usage example:
RequestSpecificsMake(NO, NO)
I've checked all common solutions for the Apple Macho-Linker error but nothing seems to work or the solutions are not relevant.
So how do I correctly implement the 'make' method for a struct?

So apparently method 2 should be the implementation and it should not be in the .h file. Naturally, I need a .m file as well. This should be the correct way to do it:
.h file
RequestSpecifics RequestSpecificsMake(BOOL includeMetaData, BOOL includeVerboseData);
.m file
RequestSpecifics RequestSpecificsMake(BOOL includeMetaData, BOOL includeVerboseData) {
RequestSpecifics specifics;
specifics.includeMetaData = includeMetaData;
specifics.includeVerboseData = includeVerboseData;
return specifics;
}
In the end I had to combine both methods! Also, by the looks of it, the extern keyword is not required.

Why dont you try
static inline instead of extern
static inline RequestSpecifics RequestSpecificsMake(BOOL includeMetaData, BOOL includeVerboseData) {
RequestSpecifics specifics;
specifics.includeMetaData = includeMetaData;
specifics.includeVerboseData = includeVerboseData;
return specifics;
}
or if you want to use extern then you need to write it in .m file.

Related

(Reflection) Calling A Method With Parameters By Function Name In Swift

Context
I have an instance of class called Solution and I have a function name as a string functionName that I want to call on the Solution instance solutionInstance. I have the parameters for the function in an array and I'd like to pass those as well.
I am using the Swift compiler to compile all of my .swift files together (swiftc with a files enumerated and then -o and the output file name) then I run the final output.
Python Example
Here is how I do this in Python:
method = getattr(solutionInstance, functionName) # get method off of instance for function
programOutput = method(*testInputsParsed) # pass the list of parameters & call the method
Purpose
This is server-side code that runs in a container to run a user's code. This code lives in a "Driver" main.swift file that calls the methods and orchestrates testing.
Problem
Swift is statically typed and I've been searching around and most sources say there is limited reflection support in Swift (and suggest to "reach into Objective-C" to get the functionality desired).
Swift is not my native language (TypeScript/JavaScript, Java, Python strongest, then C# and C++ mild, then just implementing Swift code for this feature now) so I'm not sure what that means and I haven't been able to find a definitive answer.
Question
How can I call a function by its name on a Solution class instance (it implements no protocols, at least by me) and pass an array of parameters in Swift (using reflection)? How does my setup need to change to make this happen (importing libraries, etc.)
Thank you!
Referenced Posts
Calling Method using reflection
Does Swift support reflection?
Call a method from a String in Swift
How to invoke a class method using performSelector() on AnyClass in Swift?
Dynamically call a function in Swift
First of all, as you noted Swift doesn't have full reflection capabilities and rely on the coexisting ObjC to provide these features.
So even if you can write pure Swift code, you will need Solution to be a subclass of NSObject (or implement NSObjectProtocol).
Playground sample:
class Solution: NSObject {
#objc func functionName(greeting: String, name: String) {
print(greeting, name)
}
}
let solutionInstance = Solution() as NSObject
let selector = #selector(Solution.functionName)
if solutionInstance.responds(to: selector) {
solutionInstance.perform(selector, with: "Hello", with: "solution")
}
There are other points of concern here:
Swift's perform is limited to 2 parameters
you need to have the exact signature of the method (#selector here)
If you can stick an array in the first parameters, and alway have the same signature then you're done.
But if you really need to go further you have no choice than to go with ObjC, which doesn't work in Playground.
You could create a Driver.m file of the like:
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
id call (NSObject *callOn, NSString *callMethod, NSArray <NSObject *>*callParameters)
{
void *result = NULL;
unsigned int index, count;
Method *methods = class_copyMethodList(callOn.class, &count);
for (index = 0; index < count; ++index)
{
Method method = methods[index];
struct objc_method_description *description = method_getDescription(method);
NSString *name = [NSString stringWithUTF8String:sel_getName(description->name)];
if ([name isEqualToString:callMethod])
{
NSMethodSignature *signature = [NSMethodSignature signatureWithObjCTypes:description->types];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
NSObject *parameters[callParameters.count];
for (int p = 0; p < callParameters.count; ++p) {
parameters[p] = [callParameters objectAtIndex:p];
[invocation setArgument:&parameters[p] atIndex:p + 2]; // 0 is self 1 is SEL
}
[invocation setTarget:callOn];
[invocation setSelector:description->name];
[invocation invoke];
[invocation getReturnValue:&result];
break;
}
}
free(methods);
return (__bridge id)result;
}
Add it to a bridging-header (for Swift to know about what is in ObjC):
// YourProjectName-Bridging-Header.h
id call (NSObject *callOn, NSString *callMethod, NSArray *callParameters);
And call it with a Solution.swift like this:
import Foundation
class Solution: NSObject {
override init() {
super.init()
// this should go in Driver.swift
let result = call(self, "functionNameWithGreeting:name:", ["Hello", "solution"])
print(result as Any)
}
#objc
func functionName(greeting: String, name: String) -> String {
print(greeting, name)
return "return"
}
}
output:
Hello solution
Optional(return)
Edit: compilation
To compile both ObjC and Swift on the command line you can first compile ObjC to an object file:
$ cc -O -c YouObjCFile.m
Then compile your Swift project with the bridging header and the object file:
$ swiftc -import-objc-header ../Your-Bridging-Header.h YouObjCFile.o AllYourSwiftFiles.swift -o program
working sample

How to communicate from pure C (.c files) SDK to IOS (obj-C, .m files) framework?

Preface: I have little experience with C integration in iOS, feel free to correct me on any misinterpretations I have about this.
I have a project that has a custom 2-tier "SDK" both written in C. The coreSDK makes method calls to the deviceSDK which communicates with the ios framework to execute hardware actions (ie. enable camera) or retrieve device information (ie. path to NSDocumentDirectory).
Unfortunately, due to the infrastructure, both SDK file extensions use (.h) and (.c) and cannot be changed to (.m) as some sources recommended. According to what I've read, I can create C-callbacks to the ObjC methods but that's only really viable for singletons, and the C-callback needs to be within the scope of the (.m) file.
I have tried creating a wrapper class in ObjC such that it has a C-callback from which the deviceSDK calls to, but when including the header(.h) for that (.m), the compiler seems to crash. If my understanding is correct, it's because the C-compiler cannot interpret the ObjC language contained in the (.m).
I believe theoretically is possible to write iOS apps in pure C with ObjC runtime, but ideally would rather not go down that route as what I've seen is absurdly complicated.
An example workflow
ViewController.m method calls to coreSDK method (.c)
coreSDK method calls to deviceSDK method (.c)
deviceSDK needs to retrieve (for example) NSDocumentDirectory (or enable camera)
How can I achieve this?
Code examples would be most comprehensive and appreciated.
Thanks!
These are some(not all) references I've already looked into...
How to write ios app purely in c
Pure C function calling Objective-C method
C function calling objective C functions
Using native objective-c method for C callbacks
Callback methods from C to Objective-C
Mixing C functions in an Objective-C class
How to call an Objective-C method from a C method
How to use pure C files in an objective-C project
Edit: 2016-07-21
To clarify the issue, I'm having trouble making calls from C methods in (.c) files to ObjC methods in (.m) files, or figuring out an alternative means to retrieve information such as (for example) NSDocumentsDirectory in ObjC (.m files) and passing back to C in (.c) files.
Example Code: Of course it's incorrect but it's along the lines of my expectations or what I'm hoping to achieve.
//GPS.h
#include "GPSWrapper.h"
STATUS_Code GPSInitialize(void);
//GPS.c
#include "GPS.h"
STATUS_Code GPSInitialize(void) {
GPS_cCallback();
}
//GPSWrapper.h
#import <Foundation/Foundation.h>
#interface GPSWrapper: NSObject
- (void) testObjC;
#end
//GPSWrapper.m
#import "GPSWrapper.h"
static id refToSelf = nil;
#implementation GPSWrapper
- (void) testObjC {
// just an example of a ObjC method call
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(documentsDirectory);
}
#end
static void GPS_cCallback() {
[refToSelf testObjC];
}
This line #include "GPSWrapper.h" in your example is the problem. You can't include a header that has ObjC syntax in a file that's being compiled as C. Any interface to the ObjC side that's being included in your C code needs to be broken out into its own header that contains only valid C. Here's a demo of what you need:
First, header and implementation file for the C-only stuff.
// CUtils.h
// OCFromC
#ifndef CUtils_h
#define CUtils_h
#include <stdio.h>
void doThatThingYouDo();
void doThatThingWithThisObject(const void * objRef);
#endif /* CUtils_h */
// CUtils.c
// OCFromC
// Proof that this is being compiled without ObjC
#ifdef __OBJC__
#error "Compile this as C, please."
#endif
#include "CUtils.h"
#include "StringCounterCInterface.h"
void doThatThingYouDo()
{
printf("%zu\n", numBytesInUTF32("Calliope"));
}
void doThatThingWithThisObject(const void * objRef)
{
size_t len = numBytesInUTF32WithRef(objRef, "Calliope");
printf("%zu\n", len);
}
Note that second function; if you need to, you can pass around an object reference in C land, as long as it's cloaked in a void *. There's also some casting that needs to be done for memory management. More on that below.
This is the exciting ObjC class we'll be using:
// StringCounter.h
// OCFromC
#import <Foundation/Foundation.h>
#interface StringCounter : NSObject
- (size_t)lengthOfBytesInUTF32:(const char *)s;
#end
// StringCounter.m
// OCFromC
#import "StringCounter.h"
#implementation StringCounter
- (size_t)lengthOfBytesInUTF32:(const char *)s
{
NSString * string = [NSString stringWithUTF8String:s];
return [string lengthOfBytesUsingEncoding:NSUTF32StringEncoding];
}
#end
Now, this is the important part. This is a header file that declares C functions. The header itself contains no ObjC, so it can be included in CUtils.c as you saw above.
// StringCounterCInterface.h
// OCFromC
#ifndef StringCounterCInterface_h
#define StringCounterCInterface_h
// Get size_t definition
#import <stddef.h>
size_t numBytesInUTF32(const char * s);
size_t numBytesInUTF32WithRef(const void * scRef, const char *s);
#endif /* StringCounterCInterface_h */
This is the connection point. Its implementation file is compiled as ObjC, and it contains the definitions of those functions just declared. This file imports the interface of StringCounter, and so the functions can use methods from that class:
// StringCounterCInterface.m
// OCFromC
#ifndef __OBJC__
#error "Must compile as ObjC"
#endif
#import "StringCounterCInterface.h"
#import "StringCounter.h"
size_t numBytesInUTF32(const char * s)
{
StringCounter * sc = [StringCounter new];
// Or, use some "default" object in static storage here
return [sc lengthOfBytesInUTF32:s];
}
size_t numBytesInUTF32WithRef(const void * objRef, const char * s)
{
StringCounter * sc = (__bridge_transfer StringCounter *)objRef;
return [sc lengthOfBytesInUTF32:s];
}
Now, in main or wherever you like you can exercise those functions from CUtils:
// main.m
// OCFromC
#import <Foundation/Foundation.h>
#import "StringCounter.h"
#import "CUtils.h"
int main(int argc, const char * argv[]) {
#autoreleasepool {
doThatThing();
// Create an object reference
StringCounter * sc = [StringCounter new];
// Tell ARC that I know this is dangerous, trust me,
// pass this reference along.
const void * scRef = (__bridge_retained void *)sc;
doThatThingWithThisObject(scRef);
}
return 0;
}
The bridging cast, along with its counterpart in StringCounterCInterface.m, lets you move an ObjC object through areas where ARC cannot go. It bumps the object's retain count before it is hidden in the void *, so that it will not be accidentally deallocated before you can __bridge_transfer it back to ObjC land.
One final note: If you are going to be passing object references around in C a lot, you might consider doing typedef void * StringCounterRef; and changing the signatures of everything appropriately.

call objective-c method from extern "C"

I have one temp.mm class which contains implementation for test class & extern "C" class. I am trying to call objective-c method in extern "c" class(i.e. testMethod & testMethod1).
How can i call objective-c method in extern "C" class function?.
I am new to Objective-c
I mention the example code below..
import<test.h>
#implement test
-(void)testMethod
{
//code
}
-(NSString*)testMethod1:(NSString *)value
{
//code
return value;
}
void callMethod()
{
how to call testMethod & testMethod1 in this also?
}
#end
extern "C"
{
how to call testMethod & testMethod1?
}
The C code part is (and must be) outside your class' implementation, so you'll have to create an object of test and then call it's methods, like follows:
void callMethod()
{
test *test = [[test alloc] init];
[test testMethod];
const char *yourCString = "yourCString";
[test testMethod1:[NSString stringWithCString:yourCString encoding:NSUTF8StringEncoding]];
}
You don't need the extern "C" part in the implementation (.m or .mm files), this is just needed in the header (.h files) when you want to mark them as "plain old c code" (not C++).
See: Is it required to add 'extern C' in source file also?
too call the method at initial .....
use:
[self testmethod];
[self testmethod1];
if you like to inherit this method in to another class just import the .m file.

linker error Xcode 5

Can't understand the error.
duplicate symbol _currentCount in:
/Users/selim/Library/Developer/Xcode/DerivedData/iXEN-aimjepotqgbjmlaghqjovwpsngvx/Build/Intermediates/iXEN.build/Debug-iphonesimulator/iXEN.build/Objects-normal/i386/Server.o
/Users/selim/Library/Developer/Xcode/DerivedData/iXEN-aimjepotqgbjmlaghqjovwpsngvx/Build/Intermediates/iXEN.build/Debug-iphonesimulator/iXEN.build/Objects-normal/i386/Alerts.o
ld: 1 duplicate symbol for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
1、if you declare the currentCount in .h file and include it in two .m file.
Add extern in front of currentCount declaration in .h file.
example
extern int currentCount;
2、if you declare the currentCount in two .m file.
And static in front of currentCount in .m file
example
static int currentCount
One more thing, variable declare after #implementation doesn't belong to that class , it is global value.
#interface Obj : NSObject
#end
#implementation Obj
int a = 0 ; // a declare in Obj class
#end
#interface Obj2 : NSObject
#end
#implementation Obj2
- (id)init
{
self = [super init] ;
if (self) {
a = 1 ; // you can access it in Obj2 class
}
return self ;
}
#end
Add Quartzcore framework
or check the file you don't have any duplicate file name in project.i think you add two projects thats why this error is occur.
Check it may you write a "#import file.m" instead of "#import file.h". So, In Compiles Resource will duplicate symbol file.o.
You may need to remove the duplicates in Targets Build Phases under the Compiled Sources grouping.

i have a questions when i use iOS-Universal-Framework

The iOS-Universal-Framework's page : https://github.com/kstenerud/iOS-Universal-Framework
It is an XCode project template to build universal (arm6, arm7, and simulator) frameworks for iOS.
I have build my framework by use this template,but i got a problem,i have pack all my class in the template,including a macro definition #define kCOMPANYID 2 in a .h file Macro.h,but the problem is ... the kCOMPANYID must can be modified by the one who use my framework,so the kCOMPANYID must define out of the framework,but the problem is , some classes in my framework must use the kCOMPANYID,so it is a conflict,i don't know how to do,please help me,thanks.
you should avoid #define as much as possible
one way is to make a setter/getter function to for it
e.g.
// public header file
void SetCompanyId(int value);
// int GetCompanyId(); // it can be in public header or private header
// some .m or .c or .cpp file
static int companyId;
int GetCompanyId() { return copanyId; }
void SetCompanyId(int value) { companyId = value; }
or if the user mush provide a id, just make it a global variable. you can add const to it so the value can't change
// header file in your framework
extern const int kCompanyId;
// some implementation file in user code
const int kCompanyId = 2;
then user must provided a company id otherwise it will have linker error

Resources