Search code examples
iosobjective-ccore-datamemory-managementnsdata

Delete Image Stored As Attribute of Core Data Entity


I have a core data entity called CollectedLeaf.

enter image description here

@interface CollectedLeaf :  NSManagedObject <LeafletRecognitionRequestDelegate>
{
    id <CollectedLeafDelegate> delegate_;
}

@property (nonatomic, assign) id <CollectedLeafDelegate> delegate;
@property (nonatomic, retain) NSString* leafID;
@property (nonatomic, retain) NSString* selectedSpecies;
@property (nonatomic, retain) NSString* latitude;
@property (nonatomic, retain) NSString* longitude;
@property (nonatomic, retain) NSString* altitude;
@property (nonatomic, retain) NSDate* collectedDate;
@property (nonatomic, retain) NSData * localImage;
@property (nonatomic, retain) LeafletURL* originalImageURL;
@property (nonatomic, retain) LeafletURL* segmentedImageURL;
@property (nonatomic, retain) Species* selectedSpeciesRel;
@property (nonatomic, retain) NSNumber* syncStatus;
@property (nonatomic, retain) NSDate* lastModified;
@property (nonatomic, retain) NSNumber* uploaded;
@property (nonatomic, retain) NSString* userDataset;
@property (nonatomic, retain) NSSet* CandidateSpecies;

When there isn't an internet connection, I convert the image taken with UIImagePickerController as NSData and store to my core data.

if (_internetReachability == NotReachable){
//Internet Connection Not Available

    if(imageToUpload){
    //They just tried to upload photo
    self.originalImageView.image = [UIImage imageWithData:imageToUpload];

    /*Save photo to core data here*/
    NSManagedObjectContext* context = self.collectedLeaf.managedObjectContext;
    collectedLeaf.localImage = imageToUpload;
    NSError* error;
    [context save:&error];
    }

As soon as there is internet connection, I upload the image to the server. But I know that saving images locally takes up a lot of memory, so I would like to delete the local image (just the value assigned to the attribute, not the entire object). Could I erase the image with collectedLeaf.localImage = nil ?


Solution

  • You can erase the image by setting localImage to nil.

    // Upload the image to server
    
    collectedLeaf.localImage = nil;
    
    NSError* error;
    [context save:&error];