131 @interface UserHelper : NSObject
132
133
134
135 //1、创建类方法,返回对象实例 shared default current
136
137
138
139 + (UserHelper *)sharedUserHelper;
140
141
142
143 @property (nonatomic, copy) NSString * userName;
144
145
146
147 @property (nonatomic, copy) NSString * password;
148
149
150
151 + (BOOL)isLogin;
152
153
154
155 + (void)loginWithUserName:(NSString *)userName password:(NSString *)password;
156
157
158
159 + (void)logout;
160
161
162
163 @end
164
165
166
167 // class.m
168
169 #import "UserHelper.h"
170
171
172
173 //2、创建一个全局变量
174
175
176
177 #define Path @"/Users/dahuan/Desktop/data"
178
179
180
181 static UserHelper * helper = nil;
182
183
184
185 @implementation UserHelper
186
187
188
189 //+ (void)initialize {
190
191 //
192
193 // if ([self class] == [UserHelper class]) {
194
195 // helper = [[UserHelper alloc] init];
196
197 // }
198
199 //}
200
201
202
203 + (UserHelper *)sharedUserHelper {
204
205
206
207 //3、判断对象是否存在,若不存在,创建对象
208
209 //线程安全
210
211 // @synchronized(self) {
212
213 //
214
215 // if (helper == nil) {
216
217 // helper = [[UserHelper alloc] init];
218
219 // }
220
221 // }
222
223
224
225 //gcd 线程安全
226
227 static dispatch_once_t onceToken;
228
229 dispatch_once(&onceToken, ^{
230
231 helper = [[UserHelper alloc] init];
232
233 });
234
235
236
237 return helper;
238
239 }
240
241
242
243 - (instancetype)init {
244
245
246
247 if (self = [super init]) {
248
249
250
251 NSString * data = [NSString stringWithContentsOfFile:Path encoding:NSUTF8StringEncoding error:nil];
252
253 if (data) {
254
255 NSArray * array = [data componentsSeparatedByString:@"-"];
256
257 _userName = array[0];
258
259 _password = array[1];
260
261 }
262
263 }
264
265 return self;
266
267 }
268
269
270
271 + (BOOL)isLogin {
272
273
274
275 UserHelper * helper = [UserHelper sharedUserHelper];
276
277 if (helper.userName && helper.password) {
278
279 return YES;
280
281 }
282
283 return NO;
284
285 }
286
287
288
289 + (void)loginWithUserName:(NSString *)userName password:(NSString *)password {
290
291
292
293 UserHelper * helper = [UserHelper sharedUserHelper];
294
295 helper.userName = userName;
296
297 helper.password = password;
298
299
300
301 NSArray * array = @[userName,password];
302
303 NSString * data = [array componentsJoinedByString:@"-"];
304
305 [data writeToFile:Path atomically:YES encoding:NSUTF8StringEncoding error:nil];
306
307 }
308
309
310
311 + (void)logout {
312
313
314
315 NSFileManager * fm = [NSFileManager defaultManager];
316
317
318
319 if ([fm fileExistsAtPath:Path]) {
320
321 [fm removeItemAtPath:Path error:nil];
322
323 }
324
325 }
326
327
328
329 @end
330
331
|