1

So this question is to help me better understand the inner workings of the Cocoa-touch framework and it may seem like a very simple question.

If you were to create a command line tool using Xcode, for example, using Core Data, Xcode generates methods in the "main.m" file that take in parameters in parentheses rather than the colon that is indicative of Objective-C. For example the following is the generated method declaration

static NSManagedObjectContext *managedObjectContext()

But, there is still Objective-C messages being sent inside the methods. For example,

NSString *path = [[[NSProcessInfo processInfo] arguments] objectAtIndex:0];
path = [path stringByDeletingPathExtension];
NSURL *modelURL = [NSURL fileURLWithPath:[path stringByAppendingPathExtension:@"momd"]];
model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

Is this because the main.m file is a C/C++ file and not a Objective-C file, even though they share the same file extensions? Thanks for any insight!

Guillaume
  • 21,685
  • 6
  • 63
  • 95
bdc
  • 57
  • 6

2 Answers2

0

The declaration:

static NSManagedObjectContext *managedObjectContext();

is a C function which can be declared and defined within Objective-C source files without problem. However you cannot do the opposite of declaring Objective-C classes and methods within a C source file; for example this is illegal:

myfile.c:

@interface MyObject

- (int)nothing:(int)value
{
    return value;
}

@end
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • That's true, but you can use the objc runtime to create classes in C: http://stackoverflow.com/questions/10289890/how-to-write-ios-app-purely-in-c/10290255#10290255 – Richard J. Ross III Jul 05 '12 at 17:16
-1

Basically, while Objective-C has "class methods" that can viewed as an extended version of C++ static methods, there's often no benefit in using these compared to ordinary C functions.

Even less so if you don't have a class anyway (in which case you are merely adding the Objective-C overhead).

Objective-C is called Objective-C for a reason: it's made up of "Objective-" and "C". There is no need to ignore the "C" part. And it's not too uncommon to have different ways of doing the same thing with little or even no "real" difference.

Christian Stieber
  • 9,954
  • 24
  • 23
  • Not entirely true. Class methods in Obj-C have one major advantage: you can use `self` as an object, to pass to other methods, as a delegate, or an observer, or even add iVars / associated objects! – Richard J. Ross III Jul 05 '12 at 17:16