Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pathForResource method

enter image description hereI'm playing around with imageView and there is the method [ imageWithContentsOfFile]; But actually it doesn't show anything after run it. Below the code , there is the [ imageNamed:] method and it works as usual. Any ideas? Thanks,

#import "ViewController2.h"

@interface ViewController2 ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ViewController2


- (BOOL)prefersStatusBarHidden
{
    return YES;
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.


    // just fugly don't do it

//    self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"stanford"]];


    UIBarButtonItem *shareItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:nil];
    UIBarButtonItem *cameraItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:nil];

    NSArray *actionButtonItems = @[shareItem, cameraItem];
    self.navigationItem.rightBarButtonItems = actionButtonItems;




    NSString *imgPath =[[NSBundle mainBundle] pathForResource:@"google" ofType:@"png"];
    self.imageView.image = [UIImage imageWithContentsOfFile:imgPath];


   // self.imageView.image = [UIImage imageNamed:@"google"];


}




- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




@end

I guess the problem is pathForResource method doesn't work properly somehow...

like image 496
Toshi Avatar asked Aug 01 '26 15:08

Toshi


1 Answers

If you're targeting iOS 7+, and using Asset Catalogs (which it looks like you're using, since you specified images.xcassets in one of your comments), Xcode 5 now puts the assets into a new file format. 1 file for all of the assets. This means you can not get access to the file directly using imageWithContentsOfFile:. And that's also why pathForResource:ofType: doesn't return a path.

If you need to access the file directly, you can include it as an normal image outside of an asset catalog.

You should also ask yourself if you need to access the file directly. In most cases you can use imageNamed:. Which also gives you automatic caching for the image and can improve performance.

like image 95
Dave Wood Avatar answered Aug 03 '26 14:08

Dave Wood