Question

I am testing some simple Objective-C code on Windows (cygwin, gcc). This code already works in Xcode on Mac. I would like to convert my objects to not subclass NSObject (or anything else, lol). Is this possible, and how?

What I have so far:

// MyObject.h
@interface MyObject

- (void)myMethod:(int) param;

@end

and

// MyObject.m
#include "MyObject.h"

@interface MyObject()
{ // this line is a syntax error, why?
    int _field;
}
@end

@implementation MyObject

- (id)init {
  // what goes in here?
    return self;
}

- (void)myMethod:(int) param {
  _field = param;
}

@end

What happens when I try compiling it:

gcc -o test MyObject.m -lobjc
MyObject.m:4:1: error: expected identifier or ‘(’ before ‘{’ token
MyObject.m: In function ‘-[MyObject myMethod:]’:
MyObject.m:17:3: error: ‘_field’ undeclared (first use in this function)

EDIT My compiler is cygwin's gcc, also has cygwin gcc-objc package:

gcc --version
gcc (GCC) 4.7.3

I have tried looking for this online and in a couple of Objective-C tutorials, but every example of a class I have found inherits from NSObject. Is it really impossible to write Objective-C without Cocoa or some kind of Cocoa replacement that provides NSObject?

(Yes, I know about GNUstep. I would really rather avoid that if possible...)

EDIT This works:

// MyObject.h
@interface MyObject
@end
// MyObject.m
#include "MyObject.h"
@implementation MyObject
@end

Not very useful though...

Was it helpful?

Solution

It's possible to make classes without a base class. There are a couple of things going on. First, your compiler doesn't seem to like the "()" class extension syntax. Other compilers would be OK with it. If you remove those "()" on line four of MyObject.m then your compiler will complain that you've got two duplicate interfaces for the MyObject class. For the purpose of your test you should move that _field variable into the declaration of MyObject in the header file, like:

@interface MyObject {
    int _field;
}
-(void)myMethod:(int)param;
@end

Then you can completely remove that extra @interface in the .m file. That should get you started at least.

OTHER TIPS

It's possible, but note that NSObject implements the memory allocation API in objective-c, and if you don't implement NSObject's +alloc and -dealloc or equivalent on a root class, you'll still need to implement the same functionality for every class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top