2011-01-27 68 views
0

我想創建一個嵌套數組或多維數組。如何在iPhone中創建數組數組?

在我的數據是,

  FirstName class year dept lastName 
     Bob   MBA 2000 Comp Smith 
     Jack   MS  2001 Comp McDonald 

     NSMutableArray *section = [[NSMutableArray alloc] init]; 

我希望把我的數據到部分陣列。

如:

section[0] = [FirstName,LastName]; 

section[1] = [class, year, dept]; 

所以,我怎樣才能把值放入數組這樣。 請幫我一把。

感謝

+0

對不起,但我不明白你的問題,你想要做什麼? – Robin 2011-01-27 10:59:30

+0

@Robin,我正在使用分組表格視圖並顯示該部分中的數據。所以我想拆分數組並將值存儲到具有不同索引的單個數組中。謝謝 – Pugal 2011-01-27 11:04:24

回答

2

我會建議創建一個自定義數據存儲類。你可以稱它PDPerson.h你還需要.m文件。對於每個屬性,做這樣的事情:

在.H:在.M

@interface PDPerson : NSObject{
}
@property(nonatomic, retain) NSString *firstName; @property(nonatomic, retain) NSString *lastName; @property(nonatomic, retain) NSString *class;//May want to consider renaming @property(nonatomic, retain) NSString *year; @property(nonatomic, retain) NSString *dept;
@end

然後:聲明每個屬性,像這樣

@implementation 
@synthesize firstName, lastName; 
@synthesize class, year dept; 

-(void)dealloc{ 
    [firstName release]; 
    [lastName release]; 
    [class release]; 
    [year release]; 
    [dept release]; 
} 

每當您想在陣列中創建新的「人員」時,請執行以下操作:

PDPerson *person = [[PDPerson alloc]init];

然後,您可以方便地設置對象的屬性,像這樣:

person.firstName = @"John"; 
person.lastName = @"Smith"; 
person.class = @"Math"; 
person.year = @"1995"; 
person.dept = @"Sciences";

和檢索他們:

firstNameLabel.text = person.firstName;

關於這些對象的好處是,你現在要做的是增加人對你的陣列:

NSMutableArray *personArray = [[NSMutableArray alloc] init]; 
[personArray addObject:person];
0
NSArray *section1 = [NSArray arrayWithObjects: @"1,1", @"1,2", @"1,3", nil]; 
NSArray *section2 = [NSArray arrayWithObjects: @"2,1", @"2,2", @"2,3", nil]; 
NSArray *section3 = [NSArray arrayWithObjects: @"3,1", @"3,2", @"3,3", nil]; 

NSArray *sections = [NSArray arrayWithObjects: section1, section2, section3, nil]; 


int sectionIndex = 1; 
int columnIndex = 0; 
id value = [[sections objectAtIndex:sectionIndex] objectAtIndex:columnIndex]; 
NSLog(@"%@", value); //prints "2,1" 

被警告,這是不是存儲數據的靈活方式。考慮使用CoreData或創建自己的類來表示數據。

0

你可以在一個NSArray中嵌套多個NSArray實例。

例如:從語言如C來++或Java,其中多維數組可以簡單地通過使用多個sequare括號被創建時

NSMutableArray* sections = [[NSMutableArray alloc] init]; 
for (int i = 0; i < numberOfSections; i++) 
{ 
    NSMutableArray* personsInSection = [[NSMutableArray alloc] init]; 
    [sections insertObject:personsInSection atIndex:i]; 
    for (int x = 0; x < numberOfPersons; x++) 
    { 
     Person* person = [[Person alloc] init]; 
     [personsInSection insertObject:person atIndex:x]; 
    } 
} 

這可能看起來是矯枉過正。但是Objective-C和Cocoa可以完成這些任務。