原本寫得不夠完整,因此寫了一個實際的測試例,來確認細節
1. 開啓一個專案
2. 加一個新的Class檔來做測試
3. 先在StoryBoard上加入一個Button及Label來顯示結果
4. 在calculate.h加上所需變數及method的設定
#import <Foundation/Foundation.h>
@interface calculate : NSObject
{
CGFloat x_value; // instance variables
}
@property (nonatomic) CGFloat y_value; // ARC 變數
- (void) set_x_value:(CGFloat)value;
- (CGFloat) get_x_value;
+ (calculate *) get_new_instance:(CGFloat) xvalue yvalue:(CGFloat)yvalue;
@end
5. 在calculate.m加上method的程式碼
#import "calculate.h"
@implementation calculate
@synthesize y_value;
- (void) set_x_value:(CGFloat)value
{
x_value = value*2;
}
- (CGFloat) get_x_value
{
return x_value;
}
+ (calculate *) get_new_instance:(CGFloat) xvalue yvalue:(CGFloat)yvalue
{
CGFloat temp;
calculate *xx = [[calculate alloc] init];
xx->x_value = xvalue; // set instance variable
// 兩種方法的結果相同
//xx.y_value = yvalue; // 內部使用set的method
[xx setY_value:yvalue]; // 使用synthesis所產生的method
[xx set_x_value:100]; // 呼叫 instance method
return xx;
}
@end
6. 在mainViewController.m加入所需程式碼
#import "mainViewController.h"
@interface mainViewController ()
@end
@implementation mainViewController
@synthesize cal_inst;
@synthesize showLabel;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)new_cal_instance:(id)sender {
cal_inst = [calculate get_new_instance:99 yvalue:99];
showLabel.text = [NSString stringWithFormat:@"x = %2.2f, y= %2.2f",
[cal_inst get_x_value], // 不能直接使用cal_inst->x_value, 因為protect
cal_inst.y_value
];
}
@end
7.執行結果





沒有留言:
張貼留言