好的,这是我的回答。这扩大了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