- Declare a class
@interface MyClass : NSObject {
}
- Declare View Controller Class
@interface MyViewController : UIViewController {
}
@implementation
- MyClass.m
#import "MyClass.h" @implementation MyClass @end
@class
如果要用到此程式以外的Class, 用#import 載入
Example: 在MyClass中Import AnotherClass
- AnotherClass.h
//--AnotherClass.h--
#import <Foundation/Foundation.h>
@interface AnotherClass : NSObject {
}
@end
- MyClass.h
//--MyClass.h
#import <Foundation/Foundation.h>
#import "AnotherClass.h"
@interface MyClass : NSObject {
//--an object from AnotherClass--
AnotherClass *anotherClass;
}
@end
如果在AnotherClass中也要用到MyClass, 不能在AnotherClass中也#import MyClass, 要用 @class
- AnotherClass.h
//--AnotherClass.h--
#import <Foundation/Foundation.h>
@class MyClass;
@interface AnotherClass : NSObject {
}
@end
- MyClass.h
//--MyClass.h
#import <Foundation/Foundation.h>
@class AnotherClass;
@interface MyClass : NSObject {
//--an object from AnotherClass--
AnotherClass *anotherClass;
}
@end
@class 只是先告訴Compiler, 這個anotherClass變數是Class, 稍後再定義這個變數如果真正要使用到這個Class的方法(method)和資料成員(field), 還是必須import "AnotherClass.h"進來
Class Instantiation (實例化)
MyClass *myClass = [MyClass alloc];
在Objective-C 當你宣告物件時, 必須在變數名稱前加上 * 星號
如果是primitive type(float, int, CGRect, NSInteger)則不用。
CGRect frame; //--CGRect is a structure-- int number; //--int is a primitive type-- NSString *str; //--NSString is a class
你也可以用 id type來宣告變數, id type代表這變數可以指定為任何類型(type)或是物件(object)
id myClass = [MyClass alloc]; id str;
Field (物件資料成員)
#import <Foundation/Foundation.h>
@class AnotherClass;
@interface MyClass : NSObject {
AnotherClass *anotherClass;
float rate;
NSString *data;
}
@end
Access Privileges (存取權限)
所有物件資料成員 fields的預設權限都為 @protected
- @private -- visible only to the class that declare it (只能在宣告的class中存取)
- @public -- visible to all classes (所有classes都能存取)
- @protected -- visible to the class that declares it as well as to inheriting classes(能在宣告的class和繼承的class中存取)
#import <Foundation/Foundation.h>
@interface MyClass : NSObject {
@public
float rate;
NSString *name;
}
@end
可以直接在外部Class存取設成@public的這兩個變數MyClass *myClass = [myClass alloc]; myclass->rate = 5; myClass->name = @"Hank Wang";
Reference
Beginning-iOS-4-Application-Development
The Objective-C Programming Language: Defining a Class