OK、ここに私の答えです。これはLancによって与えられたものに拡張されます。
まず、myObj1のスコープを決定する必要があります。クラスのインスタンスごとに1つ、またはアプリケーション全体に対して1つだけを必要としますか?クラスのインスタンスごとの場合は、インスタンス変数を作成し、必要に応じてインスタンス変数を作成するプロパティを設定します。例えば
@interface MyViewController : UIViewController
@property (nonatomic, readonly, retain) Obj1* myObj1;
// other stuff
@end
@implementation MyViewController
{
@private
Obj1* myObj1;
}
-(Obj1*) myObj1
{
@synchronized(self) // if you know you are single threaded you can omit the @synchronized block
{
if (myObj1 == nil)
{
myObj1 = [[Obj1 alloc] init];
}
}
return myObj1;
}
- (IBAction)btnCreateObj1:(UIButton *)sender
{
[[self myObj1] increment:intVal];
[[self myObj1] restring:@"orig string 1"];
NSString * newLabel = [self.labelObject1.text stringByAppendingFormat:@"value:%d string:%@",myObj1.value,myObj1.someString];
self.labelObject1.text = newLabel;
}
- (IBAction)btnIncrementObj1:(UIButton *)sender
{
[[self myObj1] increment: [self.textField.text intValue]];
}
あなたはシングルトン(プログラムごとに、すなわち、1つのオブジェクトのみを)必要な場合は、wizHの答えどおりに静的変数を使用することができますが、私はそれにアクセスするためのメソッドを使用して好みます。したがって、次のように動作します:
@interface MyViewController : UIViewController
@property (nonatomic, readonly, retain) Obj1* myObj1;
// other stuff
@end
@implementation MyViewController
-(Obj1*) myObj1
{
static Obj1* myObj1 = nil; // instance var moved to be a static variable
@synchronized([MyViewController class) // if you know you are single threaded you can omit the @synchronized block
{
if (myObj1 == nil)
{
myObj1 = [[Obj1 alloc] init];
}
}
return myObj1;
}
- (IBAction)btnCreateObj1:(UIButton *)sender
{
[[self myObj1] increment:intVal];
[[self myObj1] restring:@"orig string 1"];
NSString * newLabel = [self.labelObject1.text stringByAppendingFormat:@"value:%d string:%@",myObj1.value,myObj1.someString];
self.labelObject1.text = newLabel;
}
- (IBAction)btnIncrementObj1:(UIButton *)sender
{
[[self myObj1] increment: [self.textField.text intValue]];
}
変更された唯一のことは、クラスのAPIがどのように満たされているかです。 APIを使用するコードは変更する必要はありません。
ありがとうございます。驚くほど素晴らしい答え。 – iggy2012