iPhone应用程序中的SIngleton值存在问题
您好,iPhone应用程序中的singleton类有问题。 我创建了一个简单的类来可视化NSString值。 我的问题是当我尝试在textVIew中标记NSString时生成。 我调用了我的方法,Singleton类中string的值是(无效的)(我已经用debug对它进行了测试)。 你能帮我解决代码问题吗 我的代码:iPhone应用程序中的SIngleton值存在问题,iphone,objective-c,singleton,Iphone,Objective C,Singleton,您好,iPhone应用程序中的singleton类有问题。 我创建了一个简单的类来可视化NSString值。 我的问题是当我尝试在textVIew中标记NSString时生成。 我调用了我的方法,Singleton类中string的值是(无效的)(我已经用debug对它进行了测试)。 你能帮我解决代码问题吗 我的代码: #import "UntitledViewController.h" #import "SingletonController.h" @implementation Untit
#import "UntitledViewController.h"
#import "SingletonController.h"
@implementation UntitledViewController
@synthesize resetTextEvent;
@synthesize buttonSavePosition;
-(IBAction)stamp{
textEvent.text = [sharedController name];
}
- (void)viewDidLoad {
[super viewDidLoad];
sharedController = [SingletonController sharedSingletonController];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
#import "SingletonController.h"
@implementation SingletonController
@synthesize name;
static SingletonController *sharedController = nil;
+(SingletonController*)sharedSingletonController{
if(sharedController == nil){
sharedController = [[super allocWithZone:NULL] init];
}
return sharedController;
}
+ (id)allocWithZone:(NSZone *)zone
{
return [[self sharedSingletonController] retain];
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (NSUInteger)retainCount
{
return NSUIntegerMax; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
-(id)init{
self = [super init];
if (self != nil) {
name = [NSString stringWithFormat:@"hello"];
}
return self;
}
-(void) dealloc {
[super dealloc];
}
@end
这一行:
name = [NSString stringWithFormat:@"hello"];
这是有问题的<代码>名称引用的是实例变量,而不是您的属性。现在发生的事情是,您的字符串被分配给name
,但它是一个自动释放的对象。因此,在将来的某个时候,name
会自动释放并引用释放的内存
如果已将name
属性指定为retain
或copy
,则以下任一行将保留该对象:
self.name = [NSString stringWithFormat:@"hello"];
name = [[NSString stringWithFormat:@"hello"] retain];
这一行:
name = [NSString stringWithFormat:@"hello"];
这是有问题的<代码>名称引用的是实例变量,而不是您的属性。现在发生的事情是,您的字符串被分配给name
,但它是一个自动释放的对象。因此,在将来的某个时候,name
会自动释放并引用释放的内存
如果已将name
属性指定为retain
或copy
,则以下任一行将保留该对象:
self.name = [NSString stringWithFormat:@"hello"];
name = [[NSString stringWithFormat:@"hello"] retain];