MatterGoal
MatterGoal

Reputation: 16430

Use C definitions in Objective-C

I would define some helper functions, and i prefer write them in C instead of objective-C.

Which is the "best practice" to add header and implementation C file in a Objective C project ?

If i need to use Objective-c definition in my functions, what i need to include in my header C file (UIKit?) ?

Example: i'd like to create a shortcut to NSLog for NSString , can i create in my C file something similar to this code ? :

void MYLog (NSString *string){
  NSLog(@"%@",string);
}

Upvotes: 0

Views: 297

Answers (2)

Vladimir
Vladimir

Reputation: 170839

Yes sure you can use objective-c functions in your c code (and vice versa) if your source file is compiled as c/obj-c code (has .m extension or type set manually in xcode)

To make core functions work I think importing <Foundation/Foundation.h> and <UIKit/UIKit.h> should be sufficient. These headers may be already imported in your precompiled header (*.pch file) so you may not even need to import them.

If you want to extend some UIKit classes functionality consider also implementing custom class category instead of using plain c functions.

Upvotes: 2

zoul
zoul

Reputation: 104065

You can do this quite easily. You shouldn’t have to import anything, as you have UIKit and Foundation already imported by the prefix header. The logger function would look like this:

// Logger.h
void MyLog(NSString *str);

// Logger.m
#import "Logger.h"
void MyLog(NSString *str) {…}

Upvotes: 0

Related Questions