我正在尝试从FB获取配置文件图像并使用单例类保存它,但是当我尝试在UIImageView中显示它时似乎没有保存任何图像。我已经测试了获取facebook个人资料图片的代码并且它有效。为什么不使用单身?
@implementation FBSingleton
static FBSingleton *sharedInstance = nil;
// Get the shared instance and create it if necessary.
+ (FBSingleton *)sharedInstance {
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
@interface FBSingleton : NSObject
@property (nonatomic, strong) UIImage *userImage;
+ (instancetype)sharedInstance;
@end
UIImage *theImage = [[FBSingleton sharedInstance] userImage];
if (!theImage) {
// download the image from Facebook and then save it into the singleton
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString *facebookId = [result objectForKey:@"id"];
FBSingleton *sharedSingleton = [FBSingleton sharedInstance];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=large", facebookId ]]]];
sharedSingleton.userImage = image;
}
}];
}
FBSingleton *sharedSingleton = [FBSingleton sharedInstance];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(tableView.frame.size.width/2-75, 50.0f, 100.0f, 100.0f)];
[imageView setImage:sharedSingleton.userImage];
[self.view addSubview:imageView];
答案 0 :(得分:1)
你在单件类init中错过了@synchronized(self)
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;
}
答案 1 :(得分:0)
在您的情况下,当您致电[FBSingleton sharedInstance]
时,init
类的FBSingleton
方法将不会被调用,因为在+sharedInstance
中您调用[super allocWithZone]
而不是{ {1}}即最终版本必须是这样的:
[self new];