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

1

属性の数を収集してから 2 番目のパスでそれらを作成する必要がないようにする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 に答える