Nirmal Anand Nirmal Anand - 7 days ago 4x
Objective-C Question

Objective c object initializaiton

Department class



@interface Department:NSObject
@Property(assign,nonatomic,readwrite) NSString *name;
@Property(assign,nonatomic,readwrite) int id;


@synthesize name=_name;
@synthesize id=_id;

Employee class


#import "Department.h"

@interface Employee:NSObject

@Property(assign,nonatomic,readwrite) NSString *firstName;
@Property(assign,nonatomic,readwrite) NSString *lastName;
@Property(assign,nonatomic,readwrite) Department *department;


#import "Employee.h"

@synthesize firstname=_firstname;
@synthesize lastname=_lastname;
@synthesize department=_department;

Main class

#import <Foundation/Foundation.h>
#import "Department.h"
#import "Employee.h"

int main(int argc, const char * argv[]) {
@autoreleasepool {
Department *dept=[Department alloc];"dept1";;

Employee *emp=[Employee alloc];


return 0;


I have classes named Employee and Department. Employee has attributes firstName, lastName, Age, and Department. Department has Name and id.

I have declared .m and .h classes in the following way. Is this the correct way to implement a relation between department and employee class in Objective C?

Because I have implemented the concepts as per Java programming. The above program does not give any errors and prints the department name.

Please let me know if my approach is wrong.


Your approach is proper. #import makes the definitions in the imported file available to the compiler. However, most of the time, it is unnecessary and unwanted to import a header in another header (subclassing is an exception).

As you have it currently, Employee.h needn't import all of Department.h in order to be valid. It needs to know only that there is such a class upon which Employee depends.

So you can reduce it's dependency on it like this...

// in Employee.h
// #import "Department.h" ... we don't need this

// use this instead
@class Department

@interface Employee:NSObject

// ...
@Property(assign,nonatomic,readwrite) Department *department;

// in Employee.m
#import "Department.h"

A couple of side notes: (a) property should begin with lowercase 'p', (b) in recent versions gcc, we no longer need to explicitly synthesize the properties. You can omit those @synthesize lines.