Question

Basically my code heavily uses [UIImage imageNamed] which by default fetches image from app bundle.

Now I want the images to be returned from a directory deep within Documents (or library or whatever) - instead of main bundle. And since there are so many instances of imageNamed calls, I am considering to extend (read replace) UIImage ImageNamed implementation for this purpose.

I already went through this but can't quite make up what should I do, and what is best:

  1. Make a category of UIImage
  2. Create a subclass of UIImage
  3. Method swizzling

I also do not know if I have to take care of @2x images. My current bundle includes bunch of them, and I suppose my implementation will also have to take care of it. But not sure how.

Était-ce utile?

La solution

The cleanest, most elegant and easiest to maintain long term solution is to use a category on UIImage. Define a custom method on UIImage, and then use a Find & Replace to replace all your imageNamed calls to your new method.

Don't use swizzling (it will introduce weird, undocumented bugs) and is very difficult to maintain or debug. (Also, if you swizzle, it will break in places where you do want to use the default implementation of imageNamed).

There's no need to subclass UIImage for what you're trying to do because you don't need an instance method.

Autres conseils

If it's the only problem to retrive image from document directory try:

[UIimage imageWithContentsOfFile:yourFilePath];

//you can use these method to retrieve file path

- (NSString *) rootPath{
    return [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) lastObject];
}

- (NSString *) pathFoResourse : (NSString *) resourseName ofType: (NSString *)type{
    NSString *path = [[self rootPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", resourseName, type]];
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        path = [[NSBundle mainBundle] pathForResource:resourseName ofType:type];
    }
    NSLog(@"**path:%@**", path);
    return path;
}

The best and easiest way is to use Category. It makes the code readable. Subclass may confuse you during the work This Question will explain to you why no to use Method Swizzling

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top