[Bài Học Số 2] Cơ Bản Objective Cx - Pdf 17

1.1. Lớp
1.1.1. Các khái niệm cơ bản
1.1.1.1. Định nghĩa lớp
Một lớp trong Objective-C được định nghĩa gồm 2 file thành phần tương tự C, C++. Một file
*.h định nghĩa trước các biến thành phần và tên các phương thức, file *.m định nghĩa phần
thực thi cho các phương thức trong file *.h
File ClassName.h
PHP Code:
#import <headerFile.h>
@interface ClassName {
variable1 declaration;
variable2 declaration;
}
method1 declaration;
method2 declaration;
@end
Objective-C sử dụng từ khóa @interface để khai báo một tên lớp trong file h. Từ khóa @end
được sử dụng ở cuối phần khai báo.
File ClassName.m
PHP Code:
#import “ClassName.h”

@implementation ClassName
-method 1 //triển khai phương thức 1
-method 2 // triển khai phương thức 2
@end
Objective-C sử dụng từ khóa @implementation để khai báo phần thực thi thực sự của lớp
trong file m. Từ khóa @end được sử dụng ở cuối phần khai báo.
Ví dụ:
PHP Code:
MyClass.h

int att1;
NSString str1;
@protected
int att2;
@public
NSString str2;
int att3;
Mặc định khi không sử dụng từ khóa quyền truy xuất là @protected
1.1.1.3. Phương thức
Cú pháp định nghĩa một phương thức
PHP Code:
[Access Privilege](return_type) methodname: (type1) para1 : (type2) para2 (…);

Gọi phương thức
PHP Code:
[object methodname:para1 : para2…];
Ví dụ:
Khai báo
PHP Code:
-(MyClass*) constructor: (int) a : (int) b;
Triển khai
PHP Code:
-(MyClass*) constructor: (int) a : (int) b {
self = [super init];
if(self) {
var1 = a;
var2 = b;
}
return self;
}

}
PHP Code:
[myObject setX: 15 Y: 20];
1.1.2. Kế thừa
Tính kế thừa trong Objective-C tương tự trong các ngôn ngữ khác như C++,…
PHP Code:
#import “SuperClass.h”
#import <headerFile.h>

@interface ClassName:SuperClass {
variable1 declaration;
variable2 declaration;
}
method1 declaration;
method2 declaration;
@end
Ví dụ:
PHP Code:
#import<Foundation/NSObject.h>

@interface MyClass:NSObject {
int a;
int b;
}
-(void) setvara : (int) x;
-(void) setvarb : (int) y;
-(int) add;
@end
Trong Objective-C, thực sự tất cả các lớp khi tạo ra đều kế thừa từ lớp NSObject.
1.1.3. Phương thức tạo


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status