开发者

How to @synthesize a C-Style array of pointers?

I have a property defined in a class like so:

@interface myClass

UIImageView *drawImage[4];
...
@property (nonatomic, retain) UIImageView **drawImage;
...
@synthesize drawImage; // This fails to compile

I have found similar questions on StackOverflow and elsewhere, but none that really address this issue. 开发者_JAVA百科What is the most Objective-C kosher way to do this?


You can't; you have to change that retain to assign and handle memory management yourself; as you can't send -[retain] to an UIImageView ** (as it isn't an object.)

That is to say; you can't actually use @synthesize as that would lead to epic memory leaks with assign and doesn't work with retain or copy; what you need to do is to implement -drawImage and -setDrawImage: and write some actually accessor code.

But don't do that. Use an NSArray.


The most "kosher" way would be to create an NSArray of UIImageView objects, instead of a C-style array.


A problem you'll encounter is that functions can't return C-style arrays in C or Objective-C, and another problem you might face is that you can't assign a pointer type to an array type (which is what your synthesised setter may be trying to do). There are at least two solutions:

  1. Use an NSArray rather than a C-style array. This is the cleanest route, especially since you only have to manage the memory of one object rather than four.
  2. Wrap the C-style array into a struct. You can't return C-style arrays straight from functions but you can return a struct that has an array member (be aware that there is no retain/release going on).
    typedef struct {
        UIImage *image[4];
    } ImageCollection;
    ...
    @property (nonatomic, assign) ImageCollection drawImage;
    ...
    @synthesize drawImage;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜