Saving an NSArray of custom objects

心不动则不痛 提交于 2019-12-01 11:08:29

Your code to initialize the array is not actually creating instances of your UIImageExtra subclass.

UIImageExtra *illustration = (UIImageExtra *)[UIImage imageNamed:illustrationString];

returns a UIImage. Casting it doesn't do what you were intending.

UIImageExtra *scaledIllustration = [illustration adjustForResolution];

is still just a UIImage.

One straightforward-but-verbose way to approach this would be to make UIImageExtra a wrapper around UIImage. The wrapper would have a class method for initializing from a UIImage:

+ (UIImageExtra)imageExtraWithUIImage:(UIImage *)image;

And then every UIImage method you want to call would have to forward to the wrapped UIImage instance-- also being careful to re-wrap the result of e.g. -adjustForResolution lest you again end up with an unwrapped UIImage instance.

A more Objective-C sophisticated approach would be to add the functionality you want in a Category on UIImage, and then use method swizzling to replace the NSCoding methods with your category implementations. The tricky part of this (apart from the required Objective-C runtime gymnastics) is where to store your "extra" data, since you can't add instance variables in a category. [The standard answer is to have a look-aside dictionary keyed by some suitable representation of the UIImage instance (like an NSValue containing its pointer value), but as you can imagine the bookkeeping can get complicated fast.]

Stepping back for a moment, my advice to a new Cocoa programmer would be: "Think of a simpler way. If what you are trying to do is this complicated, try something else." For example, write a simple ImageValue class that has an -image method and an -extraInfo method (and implements NSCoding, etc.), and store instances of that in your array.

You can't add objects to an NSArray after init. Use NSMutableArray, that might be the issue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!