優惠券這個主題很適合練習屬性封裝,因為它的欄位結構單純(價格、使用時間、注意事項),但每一項都需要正確的記憶體管理語意:整數用 assign,字串用 copy 或 retain。
@interface Discount : NSObject {
int _price; // 打折價格
NSString *_discountTime; // 使用時間
NSString *_contentInformation; // 最終解釋權等注意事項
}
@property int price;
@property NSString *discountTime;
@property NSString *contentInformation;
- (void)showInformation:(int)price
andDiscountTime:(NSString *)discountTime
andContentInformation:(NSString *)contentInformation;
@end
@implementation Discount
@synthesize price = _price;
@synthesize discountTime = _discountTime;
@synthesize contentInformation = _contentInformation;
- (void)showInformation:(int)price
andDiscountTime:(NSString *)discountTime
andContentInformation:(NSString *)contentInformation {
_price = price;
_discountTime = discountTime;
_contentInformation = contentInformation;
NSLog(@"價格:%d 打折時間:%@ 詳細介紹:%@",
_price, _discountTime, _contentInformation);
}
// 覆寫 description,讓 NSLog(@"%@", object) 直接輸出結構化內容
- (NSString *)description {
return [NSString stringWithFormat:@"價格:%d 打折時間:%@ 詳細信息:%@",
_price, _discountTime, _contentInformation];
}
@end
@implementation Food
@synthesize foodName = _foodName;
@synthesize material = _material;
@synthesize nutrition = _nutrition;
@synthesize kindOfFood = _kindOfFood;
- (void)showInformation:(NSString *)foodName
andShowMaterial:(NSString *)material
andShowNurition:(NSString *)nutrition {
_foodName = foodName;
_material = material;
_nutrition = nutrition;
NSLog(@"%@ %@ %@", _foodName, _material, _nutrition);
}
- (NSString *)description {
return [NSString stringWithFormat:@"食品名稱:%@ 食材:%@ 營養物質:%@",
_foodName, _material, _nutrition];
}
@end
int main(int argc, const char * argv[]) {
Discount *dis = [[Discount alloc] init];
[dis showInformation:20
andDiscountTime:@"本優惠券每日上午10:30之後使用"
andContentInformation:@"本優惠券僅限中國大陸地區販售優惠券產品的麥當勞餐廳使用,具體以本店內公示為準,有效期 2013年12月4日 - 2013年12月30日;塗改或損壞無效;食品以實物為準,圖片僅供參考;本優惠券不適用於送餐服務;除食物外其他物品不在販售範圍;本優惠券不能與其他優惠活動同時使用"];
return 0;
}
一、description 比 NSLog 更好用。覆寫 description 之後,任何時候只要寫 NSLog(@"%@", dis) 就能看到完整結構,在除錯時比逐欄列印方便太多。若在 iOS 上要連記憶體位址一起顯示,則改用 debugDescription。
二、屬性宣告要帶記憶體語意。原範例的 @property NSString *discountTime 沒有寫 copy/retain,在 MRC 下預設是 assign,等於把外部傳入的字串直接指向,一旦對方釋放就會變成空指針。正確寫法:
@property (nonatomic, copy) NSString *discountTime; @property (nonatomic, copy) NSString *contentInformation;
字串一律用 copy 是 Objective-C 的鐵則,因為對方傳來的可能是 NSMutableString,若不複製,之後對方一 appendFormat: 你的屬性內容就莫名變了。
最後,Food 類別裡的 showInformation 方法與 Discount 的 showInformation 名稱相同但簽名不同,這在 Objective-C 中屬於不同 selector,不會衝突;不過實務上建議用更具描述性的命名(如 configureWithPrice:time:notice:),可讀性會更好。