我有一个单例类,我打算在整个应用程序中共享它。
它看起来像这样:
.m
@implementation PersonalGlobal
@synthesize firstName;
@synthesize lastName;
@synthesize SSN;
@synthesize customerNo;
@synthesize email;
@synthesize address;
@synthesize city;
@synthesize postalCode;
@synthesize telNo;
@synthesize mobileNo;
#pragma mark Singleton Methods
+ (id)sharedPersonal {
static PersonalGlobal *sharedPersonalGlobal = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedPersonalGlobal = [[self alloc] init];
});
return sharedPersonalGlobal;
}
- (void)dealloc {
[super dealloc];
// Should never be called
}
@end
.h
#import <foundation/Foundation.h>
@interface PersonalGlobal : NSObject {
NSString *firstName;
NSString *lastName;
NSString *SSN;
NSString *customerNo;
NSString *email;
NSString *address;
NSString *city;
NSString *postalCode;
NSString *telNo;
NSString *mobileNo;
}
@property (nonatomic, retain) NSString *firstName;
@property (nonatomic, retain) NSString *lastName;
@property (nonatomic, retain) NSString *SSN;
@property (nonatomic, retain) NSString *customerNo;
@property (nonatomic, retain) NSString *email;
@property (nonatomic, retain) NSString *address;
@property (nonatomic, retain) NSString *city;
@property (nonatomic, retain) NSString *postalCode;
@property (nonatomic, retain) NSString *telNo;
@property (nonatomic, retain) NSString *mobileNo;
+ (id)sharedPersonal;
@end
在代码中,我将字符串保存到其中:
PersonalGlobal *sharedPersonal = [PersonalGlobal sharedPersonal];
sharedPersonal.firstName = @"Some string";
但是当我改变 View 并尝试像这样访问字符串时:
PersonalGlobal *sharedPersonal = [PersonalGlobal sharedPersonal];
//Setting some textfield
sometextfield.text = sharedPersonal.firstName;
我什么也得不到。我在所有文件中都做了一个 #import "PersonalGlobal.h" 。
我可以以任何方式将更改提交给单例类吗?
谁能看到我在这里做错了什么?
谢谢!
Best Answer-推荐答案 strong>
您的实现看起来不错。如果您的单例返回唯一的一个实例,这应该可以工作。所以怀疑你的 sharedPersonal 方法。只需尝试在此方法中添加断点,看看它是否每次都创建一个新实例。对于我得到的引用 this所以问题。
如果没有,你也可以试试这个:
+(SingleTon *)getSharedInstance
{
static PersonalGlobal *sharedPersonalGlobal = nil;
if (sharedPersonalGlobal==nil)
{
sharedPersonalGlobal=[[PersonalGlobal alloc]init];
}
return sharedPersonalGlobal;
}
这对我来说是有效的代码。
关于iphone - 单例更改不保留到下查看IOS,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/15968460/
|