2016-10-15 5 views
0

カテゴリークラスObjective Cのオブジェクト

Department.h 

#import<Foundation/Foundation.h> 

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

Department.m

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

Employeeクラス

Employee.h

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

@interface Employee:NSObject 

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

Employee.m

initializaiton
#import "Employee.h" 

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

メインクラス

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

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

     Employee *emp=[Employee alloc]; 
     [email protected]"anand"; 
     [email protected]"nirmal"; 
     emp.department=dept;  

     NSLog(@"%@",emp.department.name); 
    } 

    return 0; 

} 

私は従業員とDepartmentという名前のクラスを持っています。従業員にはfirstName、lastName、Age、およびDepartmentという属性があります。部門は名前とIDを持っています。

私は.mと.hクラスを次のように宣言しました。これはObjective Cの部署と従業員のクラス間の関係を実装する正しい方法ですか?

私はJavaプログラミングに従って概念を実装しているので、上記のプログラムはエラーを出さず、部門名を出力します。

私のアプローチが間違っている場合は教えてください。

+0

こんにちはDan、私はこれがEmployeeクラス内にdepartmentオブジェクトを含める方法であるかどうかを知りたいと思います。 –

+0

完了したように部門定義をインポートすると、従業員はそのインターフェースを知ることができます。やや厳密なアプローチは、employee.hに '@class Department'を宣言し、employee.mにヘッダのインポートを行うことです。それはあなたが探しているものですか?これを編集して適切な質問にしてください。 – danh

+0

こんにちはダン私に5分を与えてください –

答えて

0

あなたのアプローチは適切です。 #importは、インポートされたファイル内の定義をコンパイラが使用できるようにします。しかし、ほとんどの場合、別のヘッダーにヘッダーをインポートする必要はありません(サブクラス化は例外です)。

現在のところ、Employee.hは有効であるためにDepartment.hをすべてインポートする必要はありません。従業員が依存しているようなクラスがあることだけを知る必要があります。

だから、あなたはそれがこのようにそれに依存だ減らすことができます...

// 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)の特性は、最近のバージョンのgccの(b)において、小文字の 'P' で始まる必要がありますもはや明示的にプロパティを合成する必要はありません。これらの行を省略することができます。

関連する問題