简体   繁体   中英

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. 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 .

最“洁净”的方法是创建UIImageView对象的NSArray而不是C样式的数组。

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; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM