Object-C 中的 Interface 與 C# 的 Interface 不太一樣,在 C# 中 Interface 可有可無,在用來傳遞資料的型別中實作 Interface 可以說是多此一舉,但在 Object-C 中 Interface 是必要的,它定義了這個型別有哪些屬性、方法。
Interface 結構 (TestModel.h)
#import <Foundation/Foundation.h>
@interface TestModel : NSObject {
}
@endImplementation 結構 (TestModel.m)#import "TestModel.h" @implementation TestModel @end
Property - Interface 部分
@interface TestModel : NSObject {
}
@property (nonatomic, retain) NSString *string;
@property (nonatomic) double ddouble;
@end| nonatomic | 不在多執行緒的狀況下可設為 nonatomic (預設為 atomic) |
| readonly | 唯讀 |
| readwrite | 可讀可寫 (預設) |
| assign | 非物件結構的給值方式 (預設) |
| retain | 使用 retain 方式更新資料,複製指標 |
| copy | 使用 copy 方式更新資料,複製資料 |
所以在一般情況下會看到 @property(nonatomic, retain) 的 NSString,這能提高些微的效率,而 int, double, char 的話則會使用 @property(nonatomic),因為這些資料型態不屬於物件,所以只能用 assign。
Property - Implementation 部分
@implementation TestModel #pragma mark - Properties @synthesize string, ddouble; @end
其實屬性的實作只是讓編譯器自動完成這兩個 Message 而已,一個取值一個給值,但這會提升開發速度,所以需要完成比較特殊的功能時可以自己加上讀寫的函數,加上去後會蓋掉現有的。
- (NSString *)string - (void)setString:(NSString *)value
Message - Interface 部分
@interface TestModel : NSObject {
}
- (id)initWithString:(NSString *)source;
- (void)print;
@end有寫在 .h 檔中的為 Public Message,寫在 .m 檔中的為 Private Message。
Message - Implementation 部分
@implementation TestModel
#pragma mark - Properties
@synthesize string, ddouble;
#pragma mark - Public Messages
- (id)initWithString:(NSString *)source
{
string = source;
return self;
}
- (void)print
{
NSLog(@"string -> %@", string);
NSLog(@"ddouble -> %@", [[NSNumber alloc] initWithDouble:ddouble]);
}
@end如果說要實作 Private Message 的話需要在 .m 檔案中加 Interface,這樣在這個 class 的 instance 中就看不到 Private Message。
@interface TestModel()
- (void)ddoubleAdd:(double)value;
@end
@implementation TestModel
#pragma mark - Properties
@synthesize string, ddouble;
#pragma mark - Private Messages
- (void)ddoubleAdd:(double)value
{
ddouble += value;
}
@endInstance
#import "TestModel.h"class 使用「+alloc」這個 Message 完成實例。
TestModel *model = [TestModel alloc];也可以透過之前撰寫的初始值設定 Message 來給初始值。
TestModel *model = [[TestModel alloc] initWithString:@"Hello"];
Property 的存取跟一般物件導向語言差不多,使用「.」來選擇物件底下的 Property。
model.string = @"CC"; NSLog(@"%@", model.string);
Public Message 的呼叫方式如下:
[model print];
0 回應:
張貼意見