2

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

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 ?)

4

2 回答 2

2

您不能以这种方式将 Objective-C 或 Core Foundation 集合与普通 C 数组混合。此外,正如您发现的那样,您需要将它们包装CTParagraphStyleSetting structsNSNumber对象中以便存储它们。真是一团糟。

我将采取的方法是进行 2 次传球;第一个确定你有多少属性,第二个生成这些属性。

  1. 遍历您的条件以找出有多少属性
  2. 分配一个 C 数组(参见 参考资料malloc())。
  3. 迭代您的条件并将属性存储在动态数组中。
  4. 使用数组创建样式。
  5. 释放数组(参见 参考资料free())。

注意我已经编辑了这个答案,因为我之前的答案已经过时了。

于 2013-03-14T09:34:25.080 回答
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与您的代码相比,请注意变量生命周期的延长。这是必要的,因为它是在之前声明的块结束之后引用的。

于 2013-03-14T09:58:09.410 回答