Search code examples
iosobjective-cmodel-view-controlleruiimagensdata

Best Way to Store a UIImage in a Model


I'm pretty new to iOS development and the MVC concept but to my understanding, the model isn't supposed to have any UI related content. I have an image in my images.xcassets folder called defaultImage that I want to set as the default image for my class when it gets initialized. This class is part of my model and has the following public interface:

#import <Foundation/Foundation.h>

@interface myClass : NSObject

@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSData *imageData;

@end

The reason I store the image as NSData is because based on my assumption of the fact that UI isn't allowed in the model, I can't use a UIImage here. However I was unable to successfully initialize imageData to contain the data of the image. I tried the following:

#import "myClass.h"

@implementation myClass

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.name = @"No Name";
    self.imageData = [[NSData alloc] initWithContentsOfFile:@"defaultImage"];
    }
    return self;
}

@end

Like I said though, imageData would contain nil. After looking around I found the following solution:

#import <UIKit/UIKit.h>
#import "myClass.h" 

@implementation myClass

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.name = @"No Name";
        self.imageData = [[NSData alloc] init];
        self.imageData = UIImagePNGRepresentation([UIImage imageNamed:@"defaultImage"]);
    }
    return self;
}

@end

So my question is, doesn't this break the rule of not allowing UI and UIKit inside the model? If not, please explain why not and if so, is there another way to do this? Thanks!


Solution

  • The best way is to have the image name or image path in the model and you can load the image wherever you need.

    #import <Foundation/Foundation.h>
    
    @interface myClass : NSObject
    
    @property (strong, nonatomic) NSString *name;
    @property (strong, nonatomic) NSString *imageName;
    
    @end
    

    Worst case, if you have to have the data in the class itself, then use as below.

    - (instancetype)init
    {
        self = [super init];
        if (self) {
            self.name = @"No Name";
            //self.imageData = [[NSData alloc] init]; //--Not required
            self.imageData = UIImagePNGRepresentation([UIImage imageNamed:@"defaultImage"]);
        }
        return self;
    }