ios - App crashes after receiving memory warning due to images loading -
i developing first app user can save 13 screenshots , swipe between in 1 view controller (full size images) , display them thumbnails on view controller. above how save image:
let filename:string = self.stickerused + ".png" var arraypaths = nssearchpathfordirectoriesindomains(.documentdirectory, .userdomainmask, true)[0] nsstring var pngfilename = arraypaths.stringbyappendingpathcomponent(filename) uiimagepngrepresentation(screenshot).writetofile(pngfilename, atomically:true) nsuserdefaults.standarduserdefaults().setobject(filename, forkey: self.stickerused) nsuserdefaults.standarduserdefaults().synchronize()
following how retrieve images. code first screenshot , setting image in uiimageview (done 12 other uiimageviews):
var defaultname:string = "sticker1.png" let path = nssearchpathfordirectoriesindomains( .documentdirectory, .userdomainmask, true)[0] nsstring let filename = nsuserdefaults.standarduserdefaults() .stringforkey("sticker1") ?? defaultname let imagepath = path.stringbyappendingpathcomponent(filename) let image = uiimage(contentsoffile: imagepath ) sticker1_view.image = resizeimage(image!, newsize: cgsizemake(overview.frame.width/4, overview.frame.height/4))
this how scale them down after loaded memory:
func resizeimage(image: uiimage, newsize: cgsize) -> (uiimage) { let newrect = cgrectintegral(cgrectmake(0,0, newsize.width, newsize.height)) let imageref = image.cgimage uigraphicsbeginimagecontextwithoptions(newsize, false, 0) let context = uigraphicsgetcurrentcontext() // set quality level use when rescaling cgcontextsetinterpolationquality(context, kcginterpolationhigh) let flipvertical = cgaffinetransformmake(1, 0, 0, -1, 0, newsize.height) cgcontextconcatctm(context, flipvertical) // draw context; scales image cgcontextdrawimage(context, newrect, imageref) let newimageref = cgbitmapcontextcreateimage(context) cgimage let newimage = uiimage(cgimage: newimageref) // resized image context , uiimage uigraphicsendimagecontext() return newimage! }
the app works fine first time. switch between 2 view controllers gets slow , memory warning leads crash. understand researching images getting cached. need clear cache or not multiple load images. or maybe in didreceivememorywarning() in order stop crashing. should ?
you can use profile(product->profile
) see, if there memory leak in program.
you can tutorial
hope can address memory issue.
Comments
Post a Comment