인터넷에서 다운로드 한 이미지를 저장하는 데 사용하려고하는 싱글 톤 클래스가 있으므로 언제든지 액세스 할 수 있습니다. 작업 흐름은 Facebook에 로그인하고 이미지를 Singleton 클래스로 다운로드합니다. 모든 것이 잘되고 이미지가 잘 표시됩니다. 그러나 앱 실행을 중단하면 그림이 더 이상 존재하지 않습니다. 누군가가 내 코드를보고 이미지를 항상 유지하기 위해 뭔가를 놓치고 있는지 확인할 수 있습니까? 앞서 말했듯이, 처음에는 잘 작동하지만, 앱을 종료하면 UIImage
은 더 이상 존재하지 않습니다.싱글 톤 클래스 유지 UIImage
FBSingleton.h
@interface FBSingleton : NSObject
@property (nonatomic, strong) UIImage *userImage;
+ (instancetype)sharedInstance;
@end
FBSingleton.m
@implementation FBSingleton
FBSingleton *sharedInstance = nil;
// Get the shared instance and create it if necessary.
+ (FBSingleton *)sharedInstance {
@synchronized(self){
if (sharedInstance == nil) {
sharedInstance = [[super allocWithZone:NULL] init];
}
}
return sharedInstance;
}
- (id)init
{
self = [super init];
if (self) {
// Work your initialising magic here as you normally would
self.userImage = [[UIImage alloc] init];
}
return self;
}
@end
의 ViewController (화상 저장 담당)
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=square&return_ssl_resources=1", facebookID]];
NSLog(@"Picture URL%@", pictureURL);
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:pictureURL];
// Run network request asynchronously
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:[NSOperationQueue mainQueue]
completionHandler:
^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError == nil && data != nil) {
// Set the image in the header imageView
// self.headerImageView.image = [UIImage imageWithData:data];
FBSingleton *sharedSingleton = [FBSingleton sharedInstance];
UIImage *image = [UIImage imageWithData:data];
sharedSingleton.userImage = image;
}
}];
다시 말하면 앱을 다시로드하면 UIImageView가 비어 있습니다. 아니면 UIImage가 비어 있습니까? 디스크/캐시에 Save/Load 기능을 만들었습니까? 아니면 온라인으로 만 만들려합니까? – gronzzz
FYI 싱글 톤을하는 더 좋은 방법은'dispatch_once'입니다 – ahwulf