iphone - 单例更改不保留到下查看IOS
<p><p>我有一个单例类,我打算在整个应用程序中共享它。
它看起来像这样:</p>
<p>.m</p>
<pre><code> @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 = [ init];
});
return sharedPersonalGlobal;
}
- (void)dealloc {
;
// Should never be called
}
@end
</code></pre>
<p>.h</p>
<pre><code>#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
</code></pre>
<p>在代码中,我将字符串保存到其中:</p>
<pre><code>PersonalGlobal *sharedPersonal = ;
sharedPersonal.firstName = @"Some string";
</code></pre>
<p>但是当我改变 View 并尝试像这样访问字符串时:</p>
<pre><code> PersonalGlobal *sharedPersonal = ;
//Setting some textfield
sometextfield.text = sharedPersonal.firstName;
</code></pre>
<p>我什么也得不到。我在所有文件中都做了一个 <code>#import "PersonalGlobal.h"</code> 。
我可以以任何方式将更改提交给单例类吗?</p>
<p>谁能看到我在这里做错了什么?
谢谢!</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您的实现看起来不错。如果您的单例返回唯一的一个实例,这应该可以工作。所以怀疑你的 <code>sharedPersonal</code> 方法。只需尝试在此方法中添加断点,看看它是否每次都创建一个新实例。对于我得到的引用 <a href="https://stackoverflow.com/questions/5720029/create-singleton-using-gcds-dispatch-once-in-objective-c" rel="noreferrer noopener nofollow">this</a>所以问题。</p>
<p>如果没有,你也可以试试这个:</p>
<pre><code>+(SingleTon *)getSharedInstance
{
static PersonalGlobal *sharedPersonalGlobal = nil;
if (sharedPersonalGlobal==nil)
{
sharedPersonalGlobal=[init];
}
return sharedPersonalGlobal;
}
</code></pre>
<p>这对我来说是有效的代码。</p></p>
<p style="font-size: 20px;">关于iphone - 单例更改不保留到下查看IOS,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/15968460/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/15968460/
</a>
</p>
页:
[1]