将数据传递给Singleton iOS

时间:2014-09-26 15:29:01

标签: ios objective-c singleton

我目前在从ViewController转移到PFFile的子类时遇到数据丢失的问题。传递的数据是要上载到用户配置文件的图像数据。这是选择图像的代码:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// Access the uncropped image from info dictionary
UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

// Dismiss controller
[picker dismissViewControllerAnimated:YES completion:nil];

// Resize image
_focusedImage.image = image;


NSData *imageData = UIImageJPEGRepresentation(image, 0.05f);
PFFile *imageFile = [PFFile fileWithName:@"Image.jpg" data:imageData];
[[imageUpload uploadImage] setImagePFFile:imageFile];
}

此视图中的登录imageFile正在正确打印。但是,当我将数据传递给我的单例类imageUpload uploadImage时,这就是数据结构的样子:

+ (imageUpload *) uploadImage
{
static imageUpload*_sharedImageUpload = nil;
_sharedImageUpload = [[self alloc] init];
_sharedImageUpload.imageData = [[NSData alloc] init];

PFUser *user = [PFUser currentUser];
_sharedImageUpload.imagePFFile = [[PFFile alloc] init];

PFFile *imageFile = [PFFile fileWithName:@"Image.jpg" data:_sharedImageUpload.imageData];


[imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
    if (!error)
    {
        [user setObject:imageFile forKey:@"image"];
        [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (!error)
            {
                NSLog(@"This should be the profile image upload");
            }
            else
            {
                NSLog(@"Something went wrong: %@", error);
            }
        }];
    }
}];

return _sharedImageUpload;
}

当我到达这一点时,系统只是将空白文件(零字节)上传到Parse。命名是正确的,它在数据库中的正确位置,但在该行的某处,文件本身的数据正在丢失。我无法弄清楚原因。有没有人有任何建议?

1 个答案:

答案 0 :(得分:6)

看起来你混淆了对象和方法。你想要的是一个单例对象,它有一个上传你的图像的方法/功能。我认为这就是你要找的东西:

//ImageUploader.h

#import <Foundation/Foundation.h>

@interface ImageUploader : NSObject
+ (instancetype)uploader;
- (void)uploadImageFile:(PFFile *)aFile;
@end

//ImageUploader.m

#import "ImageUploader.h"

@implementation ImageUploader
+ (instancetype)uploader {
    static ImageUploader * _uploader = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _uploader = [[self alloc] init];
    });

    return _uploader;
}

-(void)uploadPFFile:(PFFile *)imageFile{
    [imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (!error)
        {
            [user setObject:imageFile forKey:@"image"];
            [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (!error)
                {
                    NSLog(@"This should be the profile image upload");
                }
                else
                {
                    NSLog(@"Something went wrong: %@", error);
                }
            }];
        }
    }];
}
@end

您可以通过调用[[ImageUploader uploader]uploadImageFile:someFile]来调用它。