user4951
user4951

Reputation: 33050

In Objective-C Can you define a class in two different files?

I know one file can define many different classes. What about the other way around? Can one class is defined in several different files?

Say you want to add method or property of classes you wrote (rather than the framework classes). Can you do that?

Notice I do not want to change original .m file and I want to add property which is something category cannot do.

Upvotes: 0

Views: 184

Answers (3)

TheAmateurProgrammer
TheAmateurProgrammer

Reputation: 9392

Yes you can do that with categories.


//File1.h
@interface Object : NSObject

-(void)method;
@end

//File1.m
@implementation Object
-(void)method
{
    NSLog (@"hello");
}

@end

//File2.h
@interfacae Object(ObjectExtention) //How you declare a category
-(void)methodTwo;
@end

//File2.m
@implementation Object(ObjectExtention)
-(void)methodTwo
{
   NSLog (@"Categorie Method");
}

@end

//File3.m

#import "File1.h"
#import "File2.h"
int main()
{
    Object obj = [[Object alloc] init];
    [obj method]; //Declared in first file
    [obj methodTwo]; //Declared in second file where we had our categorie defined
    return 0;
}

You can do this with methods, however, you can't add more instance variables to a object like a categorie.

Upvotes: 0

Krizz
Krizz

Reputation: 11542

Not directly.

Alternatively:

  1. nicely - create category in other file

  2. not nicely - #include other file in main implementation file.

Upvotes: 0

UIAdam
UIAdam

Reputation: 5313

A class can only have one @implementation block, so no you can not define a class in multiple files.

If there is some reason you can't add code to the original class @implementation, the alternatives are subclassing or categories.

Upvotes: 2

Related Questions