2012-01-28

Object-C Class

在物件導向語言中使用 object 來傳遞資料是很常見的,例如 ASP.NET 中有 DTO, POCO, ViewModel...等,在 Cocoa 也需要使用 object 來傳遞資料,在 Object-C 自行實作 Class 比起 C# 來說要複雜一點。

Object-C 中的 Interface 與 C# 的 Interface 不太一樣,在 C# 中 Interface 可有可無,在用來傳遞資料的型別中實作 Interface 可以說是多此一舉,但在 Object-C 中 Interface 是必要的,它定義了這個型別有哪些屬性、方法。

Interface 結構 (TestModel.h)

#import <Foundation/Foundation.h>

@interface TestModel : NSObject {

}

@end
Implementation 結構 (TestModel.m)

#import "TestModel.h"

@implementation TestModel

@end


Property - Interface 部分

@interface TestModel : NSObject {

}

@property (nonatomic, retain) NSString *string;
@property (nonatomic) double ddouble;

@end
在 Object-C 中使用 @property 宣告屬性,設定的參數如下。
nonatomic不在多執行緒的狀況下可設為 nonatomic (預設為 atomic)
readonly唯讀
readwrite可讀可寫 (預設)
assign非物件結構的給值方式 (預設)
retain使用 retain 方式更新資料,複製指標
copy使用 copy 方式更新資料,複製資料
*assign, retain, copy 區別
所以在一般情況下會看到 @property(nonatomic, retain) 的 NSString,這能提高些微的效率,而 int, double, char 的話則會使用 @property(nonatomic),因為這些資料型態不屬於物件,所以只能用 assign。

Property - Implementation 部分

@implementation TestModel
#pragma mark - Properties
@synthesize string, ddouble;

@end
在 Implementation 要用 @synthesize 完成屬性的實作。
其實屬性的實作只是讓編譯器自動完成這兩個 Message 而已,一個取值一個給值,但這會提升開發速度,所以需要完成比較特殊的功能時可以自己加上讀寫的函數,加上去後會蓋掉現有的。
- (NSString *)string
- (void)setString:(NSString *)value


Message - Interface 部分

@interface TestModel : NSObject {
   
}

- (id)initWithString:(NSString *)source;
- (void)print;

@end
Message 也就是 Method,static message 的話要用「+」,一般的 message 則是使用「-」。
有寫在 .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
在 Implementation 中要實作 Message 的邏輯。
如果說要實作 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;
}

@end


Instance

在.h檔前方必須先加上
#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 回應:

張貼意見