开发者

setting image to button -> take up lots of memory ? what should i do then

basically im running my apps with instruments and found out that by just setting a background image to the UIButton, it takes up 6mb of data(which i do not want in case low-memory warnings). i read around and found out that since the button has been assigned the image, it retains it(and the memory).

How should i code it then?My current codes are as below. 开发者_StackOverflow社区Btw im new to iPhone development so please tell me what to do.

btw this button would just bring me to another view. is there anyway to release the memory that was allocated to this image?

.m file

 -(void)viewDidLoad{
UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"MainScreen.png"]];
selectionScreen.backgroundColor = background;
[background release]
}


You mentioned in comment above that your .png is under 300k. That's perhaps a touch big, but you're actually not looking at the right thing. A png gets expanded to a native CGImage object. I usually figure a 32-bit image with alpha takes up width * height * 4 bytes of memory. That's pretty much guaranteed to be bigger than the PNG it gets expanded from, and in your case could be quite big indeed. Enough so that the docs recommend not instantiating UIImages bigger than 1024 x 1024.

Now, one solution could be that -initWithPatternImage can take a small piece of your background, and will tile it when it's drawn. So your first shot at solving this would be to provide that method as small an image as possible, and let it tile to bigger sizes.

Second thing, the retention. You're correctly releasing your UIColor object after setting it on the background. You WANT that object you set it on to retain it! In a world of infinite memory, you'd want that button to retain its background color until the viewcontroller it's on gets dealloc'ed. If it's still huge and you really have to get rid of it before backing out of the view controller (say when you push to a new UINavigationController view or something), you could try setting background to nil (or a system default color maybe) in -viewDidDisappear and re-building your background in -viewWillAppear.


Wheb viewWillDisappear, you can set backgroundColor as another color, and release the background color you made.

-(void)viewWillDisappear:(BOOL)animated
{
  // release original backgroundColor
  // default backgroundColor is nil by UIView class reference.
  selectionScreen.backgroundColor = nil;     

}

Hope this can help you.


Did you try using something like:
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:/frameOfChoice/];
[button setBackgroundImage:[UIImage imageNamed:@"MainScreen.png"] forControlState:UIControlStateNormal];

I'm not sure how this effects the memory usage tho.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜