Objective-C 创建一个 C 数组属性

标签 objective-c c memory

我想创建一个由 CGRect 指针数组组成的属性,数字在开始时没有定义,所以我想创建一个指向包含此数组开头的内存区域的指针的指针。这似乎很困难,我看到了不同的答案并将我的解决方案基于此。
到目前为止,我已经写了:

@interface ViewController ()
@property (assign) CGRect * rectArray;
@property (strong, nonatomic) NSArray * hotspots;
@end

@implementation ViewController



- (CGRect *) createRectArray {
    int count = _hotspots.count;
    _rectArray = malloc(sizeof(CGRect*)*count);
    for (int i = 0; i<count; i++) {
        CGRect currentFrame = ((UIView*)_hotspots[i]).frame;
        _rectArray[i] = &currentFrame;
    }

    return _rectArray;
}
@end

但是编译器提示说赋值不正确。

我猜测正确的变量可能不是 CGRect * rectArray,而是双重间接 CGRect ** rectArray。
那是对的吗?
[更新]
实际上,我想做的事情没有意义...因为属性 -frame 返回 CGRect 的副本而不是指向它的指针,所以我想直接快速访问它的想法已经不复存在了。

最佳答案

以下代码正确访问了 rectArray

@interface ViewController ()
//array of pointers 
@property (assign) CGRect **rectArray;
@property (strong, nonatomic) NSArray * hotspots;
@end

@implementation ViewController


- (CGRect **) createRectArray {
    int count = _hotspots.count;
    _rectArray = malloc(sizeof(CGRect*)*count);

    for (int i = 0; i<count; i++) {
        //this will never work, the frame returned from UIView is a temporary which will get released!
        CGRect currentFrame = ((UIView*)_hotspots[i]).frame;
        _rectArray[i] = &currentFrame;
    }

    return _rectArray;
}

- (void)dealloc {
   free(_rectArray);
}
@end

但是,正如我在评论中所写,这是行不通的。 [UIView frame] 返回一个 C 结构。这与原始变量(NSIntegerlong 等)的行为相同。它被复制了。 ¤tFrame 是对本地堆栈变量的引用,当代码超出范围时(for 迭代结束,方法结束),它将被释放。它不会做你所期望的。访问存储的指针会使您的应用程序崩溃。

您可以通过以下两种方法轻松实现您期望的功能

- (void)setFrame:(CGRect)frame forHotspotAtIndex:(NSUinteger)index {
    UIView* hotspot = [self.hotspots objectAtIndex:index];
    hotspot.frame = frame;
}

- (CGRect)frameForHotspotAtIndex:(NSUinteger)index {
    UIView* hotspot = [self.hotspots objectAtIndex:index];
    return hotspot.frame;
}

关于Objective-C 创建一个 C 数组属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16690644/

相关文章:

objective-c - 从一个模态视图无缝切换到另一个模态视图,不显示纯色背景

objective-c - 在 Objective C 中为 NSObjects 存储的保留计数在哪里

ios - Parse.com WhereKey :containedIn doesn`t show any results - objectId

c - 将文本读入 C。出现错误的执行错误

c - inet_ntop 重复循环IP

c - 在 ansi c 中用 pascal 替换 readln 有什么很酷的功能吗?

c++ - 编辑其他进程内存

iphone - 如何拦截点击 UITextView 中的链接?

android - android中的dalvik堆和 native 堆有什么区别?哪一个是固定的。?

c# - 如何计算我的代码的内存使用量以找出 C# 的最佳方式?