2010-06-19 34 views
0

我喜欢从我有的typedef结构中创建一个数组。带结构的NSMutableArray

它工作正常,当我与固定的数组大小工作。但只是要开放更大的数组我想我必须使用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 

任何简短的演示,工程,将不胜感激:)仍在学习

THX 克里斯

+0

你的数组正在返回一个NSValue的实例...这就是你放在那里的东西。所以,阅读:[[array objectAtIndex:2] getValue:&data]; – 2010-06-19 16:15:07

+0

行! :) THX,现在它的作品:) – 2010-06-19 16:34:43

回答

6

这是极不寻常的混合含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 

这也使得这样的,你需要添加业务逻辑的时间到上述数据记录,你已经有一个方便的地方这样做。