iPhone帮助单身类

时间:2011-02-18 20:21:27

标签: iphone objective-c singleton

问候,

我正在研究Matt Gallagher创建单例类的宏。 http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html

基本上,我有一个包含多个视图的应用程序,我希望能够使用单例类从这些视图中访问“全局”数据。

我基本上有三个我想在这个类中访问的字符串:NSString * uname,NSString * details和NSString * selectedDetails。

我是否需要在每个类中使用静态变量制作三个单例类?

另外,如何获取和设置字符串变量uname,details和selectedDetails?

我有点混淆所有这些单身人士的东西(我今天才遇到这样的事情!)我想知道是否有人能指出我正确的方向。

非常感谢,

以下是我完成的一些代码:

#import <Foundation/Foundation.h>

@interface Details : NSObject{

}
+(XXX *)sharedXXX;
@end


#import "Details.h"
#import "SynthesizeSingleton.h"

@implementation Details
SYNTHESIZE_SINGLETON_FOR_CLASS(XXX);
@end

3 个答案:

答案 0 :(得分:1)

  

我是否需要在每个类中使用静态变量制作三个单例类?

没有。只需创建一个包含所有三个的。

  

另外,如何获取和设置字符串变量uname,details和selectedDetails?

您可以获得对单身人士的引用,通常使用以下内容:

MySingleton *singleton = [MySingleton sharedInstance];

然后你像使用任何其他对象一样使用它:

singleton.uname = @"Example";

你确定你真的需要单身吗?如果是用户数据,请将其与NSUserDefaults一起存储?

答案 1 :(得分:1)

好的,我在Jim的帮助下自己解决了这个问题......

//.h:
import <Foundation/Foundation.h>

@interface Details : NSObject {
    NSString *global_uname;
    NSString *global_details;
    NSString *global_selectedDetails;
}
@property (nonatomic,retain) NSString *global_uname,*global_details,*global_selectedDetails;

+(Details*) sharedDetails;
@end




//.m:
#import "Details.h"
#import "SynthesizeSingleton.h"

@implementation Details
SYNTHESIZE_SINGLETON_FOR_CLASS(Details);
@synthesize global_uname,global_details,global_selectedDetails;
@end

然后你得到/设置使用:

[Details sharedDetails].global_uname

答案 2 :(得分:-1)

T1=[[UITextField alloc] init];
    T2=[[UITextField alloc] init];
    T3=[[UITextField alloc] init];
    T4=[[UITextField alloc] init];
    [T1  addTarget:self action:@selector(goto:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [T2  addTarget:self action:@selector(goto:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [T3  addTarget:self action:@selector(goto:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [T4  addTarget:self action:@selector(goto:) forControlEvents:UIControlEventEditingDidEndOnExit];

    T1.backgroundColor=[UIColor whiteColor];
    T2.backgroundColor=[UIColor whiteColor];
    T3.backgroundColor=[UIColor whiteColor];
    T4.backgroundColor=[UIColor whiteColor];
    T1.placeholder=@"companyname";
    T2.placeholder=@"address";
    T3.placeholder=@"contactno";
    T4.placeholder=@"noofemp";

    T1.frame=CGRectMake(60, 0, 100, 30);
    T2.frame=CGRectMake(60, 60, 100, 30);
    T3.frame=CGRectMake(60, 110, 100, 30);
    T4.frame=CGRectMake(60, 160, 100, 30);
相关问题