可变大小的struct数组?

时间:2013-03-14 09:22:09

标签: ios arrays core-text

我想创建一个结构数组,其大小只在运行时知道

NSMutableArray *styleSettingsArray = [NSMutableArray array];

NSString *fontAlignmentAttribute = [element attributeNamed:@"TextAlignment"];
if(fontAlignmentAttribute)
{
    CTTextAlignment alignment = [self getTextAlignment:fontAlignmentAttribute];
    CTParagraphStyleSetting styleSetting = {kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment), &alignment};
    [styleSettingsArray addObject:[NSValue valueWithBytes:&styleSettings objCType:@encode(CTParagraphStyleSetting)]];
}

// other posible attributes

CTParagraphStyleRef paragraphStyleRef = CTParagraphStyleCreate((__bridge const CTParagraphStyleSetting *)(styleSettingsArray), [styleSettingsArray count]);
[dictionary setObject:(__bridge id)(paragraphStyleRef) forKey:(NSString*)kCTParagraphStyleAttributeName];
CFRelease(paragraphStyleRef);

此代码不起作用。

编辑:

CTParagraphStyleCreate获取指向CTParagraphStyleSetting数组的指针,例如

CTParagraphStyleSetting styleSettings[] = {
    { kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment), alignment},
    {...},
    {...}
};

如何分配此数组,并在不知道其中包含多少内容的情况下添加内容? (我如何使用malloc?)

2 个答案:

答案 0 :(得分:2)

您不能以这种方式将Objective-C或Core Foundation集合与纯C阵列混合使用。另外,您已经发现需要将CTParagraphStyleSetting structs包装在NSNumber个对象中以便存储它们。真是一团糟。

我采取的方法是做2次通过;第一个确定你拥有多少属性,第二个属性来生成这些属性。

  1. 迭代您的条件以找出有多少属性
  2. 分配C数组(请参阅malloc())。
  3. 迭代您的条件并将属性存储在动态数组中。
  4. 使用数组创建样式。
  5. 释放阵列(请参阅free())。
  6. 注意我已经编辑了这个答案,因为之前的答案已经过时了。

答案 1 :(得分:1)

为了避免必须收集属性的数量,然后在第二次传递中创建它,我建议使用NSMutableData而不是普通的C数组或malloc。这种风格允许您只使用最少的更改来使用现有代码:

NSMutableData *styleSettingsArray = [NSMutableData array];

NSString *fontAlignmentAttribute = [element attributeNamed:@"TextAlignment"];
CTTextAlignment alignment;
if (fontAlignmentAttribute)
{
    alignment = [self getTextAlignment:fontAlignmentAttribute];
    CTParagraphStyleSetting styleSetting = { kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment), &alignment};
    [styleSettingsArray appendBytes:&styleSetting length:sizeof(styleSetting)];
}

// other posible attributes
CTParagraphStyleRef paragraphStyleRef = CTParagraphStyleCreate([styleSettingsArray bytes], [styleSettingsArray length] / sizeof(CTParagraphStyleSetting));

修改:请注意alignment变量的生命周期延长,与您的代码进行比较。这是必要的,因为它是在之前声明的块结束之后引用的。

相关问题