如何在iPhone中创建Array数组?

时间:2011-01-27 10:49:26

标签: iphone arrays nested

我想创建一个嵌套数组或多维数组。

在我的数据中,

         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];

那么我怎样才能将值放入数组中。 请帮帮我。

由于

3 个答案:

答案 0 :(得分:2)

我建议您创建一个自定义数据存储类。您可以将其称为PDPerson.h您还需要.m文件。对于每个房产,请执行以下操作:

在.h 中:声明每个属性,如:

@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

然后在.m:

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

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

每次要在数组中创建新的“Person”时,请执行以下操作:

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

然后,您可以轻松设置对象的属性,如下所示:

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

并检索它们:

firstNameLabel.text = person.firstName;

关于这些对象的好处是你现在要做的就是将person对象添加到你的数组中:

NSMutableArray *personArray = [[NSMutableArray alloc] init];
[personArray addObject:person];

答案 1 :(得分: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或创建自己的类来表示数据。

答案 2 :(得分:0)

您可以在NSArray中嵌套多个NSArray实例。

例如:

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];
    }
}

当来自C ++或Java等语言时,这似乎有些过分,因为只需使用多个方括号就可以创建多维数组。但这是用Objective-C和Cocoa完成的。