gpt4 book ai didi

ios - 单例不返回任何图像

转载 作者:行者123 更新时间:2023-11-29 02:47:59 27 4
gpt4 key购买 nike

我正在尝试从 FB 获取个人资料图像并使用单例类保存它,但是当我尝试在 UIImageView 中显示它时它似乎没有保存任何图像。我已经测试了正在获取 facebook 个人资料图像的代码并且它可以正常工作。为什么它不能使用单例工作?

FBSingleton.h

@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

FBSingleton.h

@interface FBSingleton : NSObject

@property (nonatomic, strong) UIImage *userImage;

+ (instancetype)sharedInstance;
@end

ViewController.h - 保存 UIImage

    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;

}
}];




}

AnotherViewController.m - 获取表单单例类

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];

最佳答案

你在单例类初始化中错过了@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;
}

关于ios - 单例不返回任何图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24870869/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com