好的,這是我的回答。這擴大了Lanc給出的。
首先,您需要確定myObj1的範圍應該是什麼。你想每個實例的類或整個應用程序只有一個。如果它是每個類的實例,則創建一個實例變量並擁有一個按需創建它的屬性。例如
@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]];
}
如果你需要一個單身(即僅針對每個程序對象),你可以使用一個靜態變量按照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 2012-02-29 21:46:09