Reputation: 1375
using iOS 4.1 SDK. I am using 2 small images in each row of a UITableView. I wanted to know which of the following 2 methods was better, also is Method 1 valid at all?
- (void)viewDidLoad
{
// create the images amd assign to class member variable
NSString *imgStr1 = [[NSBundle mainBundle] pathForResource:@"someImg1"
ofType:@"png"];
UIImage* img1 = [[UIImage alloc] initWithContentsOfFile:imgStr];
self.image1 = img1;
[img1 release];
NSString *imgStr2 = [[NSBundle mainBundle] pathForResource:@"someImg2"
ofType:@"png"];
UIImage* img2 = [[UIImage alloc] initWithContentsOfFile:imgStr2];
self.image2 = img2;
[img2 release];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"cellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
cellIdentifier];
if (cell == nil)
{
//create image views here
..........................
}
/ assign images from viewDidLoad to imageView here
UIImageView *img1View = (UIImageView *)[cell viewWithTag:kImg1Tag];
[img1View setImage:self.img1];
etc....
}
OR should i just do this in the cellForRowAtIndexPath
[img1View setImage:[UIImage imageNamed:@"img1.png"];
Upvotes: 0
Views: 296
Reputation: 58448
In this case I would go with imageNamed:
as it will cache the two images and properly respond to memory warning situations.
Method one is valid, but there is little difference between it and using imageNamed:
. Images created with imageNamed:
will be cleared out if the device needs to reclaim memory. Unless you clear the images created in method one yourself when you receive a memory warning they will stay in memory.
It's also less code and less that you have to worry about, which is always better. Less code == less bugs.
Upvotes: 1
Reputation: 4138
I think the simplest way is to use UIImage
's imageNamed:
method, which loads the image from the app bundle and keeps it in cache.
This way you would only have to set the cell's UIImageView's image to [UIImage imageNamed:@"img1.png"]
in cellForRowAtIndexPath:
method.
Another point, if you cell has many subviews, I think subclassing it and adding different subviews as class properties is better. Then you only have to cast it when getting it from dequeueReusableCell
and it allows you to modify subviews without using tags and casting everytime.
Upvotes: 0