這個練習示範如何用類別繼承來建模一個微博系統:先有通用的「人」,再延伸出「博主」,最後由「微博」聚合這些角色與內容屬性。它涵蓋了 property 宣告、description 重寫與 isKindOfClass 的型別檢查。
// main.m
#import <Foundation/Foundation.h>
#import "Person.h"
#import "BlogMaster.h"
#import "Microblog.h"
int main(int argc, const char * argv[]) {
Person *person = [[Person alloc] init];
[person showName];
NSLog(@"%@", person);
Person *man = [[Person alloc] init];
[man showName];
return 0;
}
// Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject {
NSString *_name; // 名字
int _age; // 年齡
NSString *_birthday; // 出生年月
char _sex; // 性別
NSString *_address; // 所在地
NSString *_emotion; // 感情狀況
NSString *_bloodType; // 血型
}
@property NSString *name;
@property int age;
@property NSString *birthday;
@property char sex;
@property NSString *address;
@property NSString *emotion;
@property NSString *bloodType;
- (void)showName;
@end
// Person.m
#import "Person.h"
@implementation Person
- (void)showName {
NSLog(@"打印人的名字");
}
- (NSString *)description {
return [NSString stringWithFormat:
@"名字=%@ 年齡=%d 出生日期=%@ 性別=%c 住址=%@ 感情狀況=%@ 血型=%@",
_name, _age, _birthday, _sex, _address, _emotion, _bloodType];
}
@end
// BlogMaster.h
#import "Person.h"
@interface BlogMaster : Person
@end
// BlogMaster.m
#import "BlogMaster.h"
@implementation BlogMaster
- (void)showName {
NSLog(@"博主的名字");
}
@end
// Microblog.h
#import <Foundation/Foundation.h>
@interface Microblog : NSObject {
NSString *_registerTime; // 註冊時間
NSString *_introductionAboutBlog; // 簡介
NSString *_blogContent; // 博客內容
NSString *_commentContent; // 評論內容
int _commentAmount; // 評論數量
int _praiseAmount; // 點讚數量
NSString *_publishTime; // 發表時間
int _transpond; // 轉發數量
}
@property NSString *registerTime;
@property NSString *introductionAboutBlog;
@property NSString *blogContent;
@property NSString *commentContent;
@property NSString *publishTime;
@property int commentAmount;
@property int praiseAmount;
@property int transpond;
@end
// Microblog.m
#import "Microblog.h"
@implementation Microblog
- (NSString *)description {
return [NSString stringWithFormat:
@"博客內容=%@ 評論數量=%d 點讚數量=%d 發表時間=%@ 轉發數量=%d",
_blogContent, _commentAmount, _praiseAmount, _publishTime, _transpond];
}
@end
BlogMaster 繼承 Person 是合理的——博主本質上就是人,只是多了一些行為。但若日後需要區分「一般使用者」與「博主」,用繼承會讓類別層級迅速膨脹,這時改用具名的 role 屬性或 protocol 會更合適。[person isKindOfClass:[BlogMaster class]],成立後才能安全轉型:if ([person isKindOfClass:[BlogMaster class]]) {
BlogMaster *master = (BlogMaster *)person;
[master showName];
}
BlogMaster *_blogMaster 成員註解掉了,導致微博與作者失去關聯。真實設計中,Microblog 應該有一個 Person *author 屬性,並在 initWithAuthor:content: 時注入,這樣才能正確表達「誰發了這條微博」。NSDate 儲存,顯示時再格式化。