gpt4 book ai didi

cocoa - NSMutableArray 与结构

转载 作者:行者123 更新时间:2023-12-03 17:29:47 25 4
gpt4 key购买 nike

我喜欢用我拥有的 typedef 结构创建一个数组。

当我使用固定数组大小时,它工作得很好。但为了对更大的数组开放,我想我必须用 nsmutable 数组来制作它。但在这里我没有让它运行

    //------------ test STRUCT
typedef struct
{
int id;
NSString* picfile;
NSString* mp3file;
NSString* orgword;
NSString* desword;
NSString* category;
} cstruct;

//------- Test Fixed Array
cstruct myArray[100];
myArray[0].orgword = @"00000"; // write data
myArray[1].orgword = @"11111";

NSLog(@"Wert1: %@",myArray[1].orgword); // read data *works perfect



//------ Test withNSMutable
NSMutableArray *array = [NSMutableArray array];
cstruct data;
int i;
for (i = 1; i <= 5; i++) {
data.orgword = @"hallo";
[array addObject:[NSValue value:&data withObjCType:@encode(struct cstruct)]];
}

data = [array objectAtIndex:2]; // something is wrong here
NSLog(@"Wert2: %@",data.orgword); // dont work

任何有效的简短演示将不胜感激:)仍在学习

谢谢克里斯

最佳答案

将包含 Objective-C 类型的结构与 Objective-C 中的对象混合在一起是非常不寻常的。虽然您可以使用 NSValue 来封装结构,但这样做很脆弱,难以维护,并且在 GC 下可能无法正常运行。

相反,简单的类通常是更好的选择:

 @interface MyDataRecord:NSObject 
{
int myRecordID; // don't use 'id' in Objective-C source
NSString* picfile;
NSString* mp3file;
NSString* orgword;
NSString* desword;
NSString* category;
}
@property(nonatomic, copy) NSString *picfile;
.... etc ....
@end

@implementation MyDataRecord
@synthesize picfile, myRecordID, mp3file, orgword, desword, category;
- (void) dealloc
{
self.picfile = nil;
... etc ....
[super dealloc];
}
@end

这也使得当您需要向所述数据记录添加业务逻辑时,您已经有一个方便的位置来执行此操作。

关于cocoa - NSMutableArray 与结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3076176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com