ios/objective c/singleton:将用户标识存储在会话变量中 [英] ios/objective c/singleton: Storing userid in session variable
本文介绍了ios/objective c/singleton:将用户标识存储在会话变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在单例中(针对用户ID)定义了一个NSInteger,并在另一个类中对其进行访问.但是,尽管我设法摆脱了错误消息,但仍可以构建,但应用程序在碰到行时便崩溃了.
I defined an NSInteger in a singleton (for userid) and access it in another class. However, while I have managed to get rid of error messages so it builds, the app crashes when it hits line.
这是初始定义;
Session.h
@interface Session : NSObject
@property (assign,nonatomic) NSInteger *userid;
+ (IDSession *)sharedInstance;
Session.m
@implementation Session
+ (Session *)sharedInstance {
static Session *session;
if (!session){
session = [[Session alloc] init];
NSInteger *userid=1;
//include this class in other class and reference userid with [Session sharedInstance].userid
}
return session;
}
试图在导入到该类之上的其他类中获取会话
Attempt to get session in other class that imports above class
in save method:
NSInteger *number =[Session sharedInstance].userid;//crashes here log says (lldb)
将对解决此问题的任何建议表示感谢.
Would appreciate any suggestions on how to fix this.
谢谢.
推荐答案
以下使用NSString而不是数字并设置局部变量而不是属性的代码有效:
The following code using NSString instead of numbers and setting a local variable rather than a property works:
Session.h
@interface IDSession : NSObject
@property (readonly, copy) NSString *userid;
+ (IDSession *)sharedInstance;
@end
Session.m
#import "IDSession.h"
@interface IDSession()
@property (readwrite,copy)NSString * userid;
@end
@implementation IDSession
+ (IDSession *)sharedInstance {
static IDSession *session;
if (!session){
session = [[IDSession alloc] init];
//include this class in other class and reference userid with [IDSession sharedInstance].userid
NSString * userid = @"1";
}
return session;
}
@end
in retrieving class.
#import "session.h"
NSString *userid =[Session sharedInstance].userid;
NSLog(@"userid retrieved from session variable is %@",userid);
这篇关于ios/objective c/singleton:将用户标识存储在会话变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文