我想创建一个结构数组,其大小只在运行时知道
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?)
答案 0 :(得分:2)
您不能以这种方式将Objective-C或Core Foundation集合与纯C阵列混合使用。另外,您已经发现需要将CTParagraphStyleSetting
structs
包装在NSNumber
个对象中以便存储它们。真是一团糟。
我采取的方法是做2次通过;第一个确定你拥有多少属性,第二个属性来生成这些属性。
malloc()
)。free()
)。注意我已经编辑了这个答案,因为之前的答案已经过时了。
答案 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
变量的生命周期延长,与您的代码进行比较。这是必要的,因为它是在之前声明的块结束之后引用的。