NSString中的NSMutableArray

时间:2011-04-26 22:45:01

标签: objective-c nsstring nsmutablearray

在没有编程的10年后(当时在Delphi中),我开始学习 Objective-C的。我承认我遇到了很多问题,因为这种方法非常不同。

我想创建一个简单的表,其中每行包含几个 NSString变量。一个例子:

ID Firstname Lastname

01  FN1        LN1

02  FN2        LN2

我的表:

NSString * FirstName, * LastName;

NSMutableArray * person = [NSMutableArray arrayWithObjects: firtsname, lastname, nil];

问题在于我无法添加包含2个NSString的行,例如:

FirstName = @ "FN1";

LastName = @ "LN1";

[person AddObject: FirstName, LastName]; 

FirstName = @ "FN2";

LastName = @ "LN2";

[person AddObject: FirstName, LastName]; 

//etc. ...

我知道AddObject只能添加1个对象,但它是为了解释我的例子的概念。

如何在我的示例中同时添加2个对象?

然后,我如何管理/检索对象NString“1”(firstName)& NString“2”(lastName)由索引(i);

我承认我找不到发展的逻辑,你的回答会非常有帮助。

非常感谢您的回复。


编辑:

我有一个奇怪的问题。我的.m:

Person *pers = [[Person alloc]init];

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

[pers setFirstName:@"FN 1"]; // = pers.firstName;
[pers setLastName:@"LN 1"]; // = pers.lastName;
[myarray addObject:pers];

[pers setFirstName:@"FN 2"];
[pers setLastName:@"LN 2"];
[myarray addObject:pers];

[pers release];

NSLog(@"count: %d", [myarray count]);

for(int i = 0; i < [myarray count]; i++)
    {
    pers = [myarray objectAtIndex:i];
    NSLog(@"%d %@ %@ %@", i, pers, pers.firstName, pers.lastName);
    }

[myarray release];

我的NSLog是: 2011-04-27 19:07:57.582 temp [11724:903] count:2

2011-04-27 19:07:57.584 temp [11724:903] 0 FN 2 LN 2

2011-04-27 19:07:57.585 temp [11724:903] 1 FN 2 LN 2

如你所见,我有两次FN 2 LN 2。对象“pers”具有两倍相同的值

正常吗?

2 个答案:

答案 0 :(得分:2)

最简单的方法是制作一个非常简单的模型类:

“Person.h”

#import <Foundation/Foundation.h>

@interface Person : NSObject {
    NSString *firstName;
    NSString *lastName;
}

@property (readwrite, copy) NSString *firstName;
@property (readwrite, copy) NSString *lastName;

@end

“Person.m”

#import "Person.h"

@implementation Person

@synthesize firstName, lastName;

- (void)dealloc
{
    [firstName release];
    firstName = nil;

    [lastName release];
    lastName = nil;

    [super dealloc];
}

@end

这将允许您使用addObject:,因为它在技术上是一个对象,您只能在其中存储多个数据。一个例子如下:

//...
Person *p1 = [[Person alloc] init];
[p1 setFirstName:@"First Name"];
[p2 setLastName:@"Last Name"];

[personArray addObject:p1];
[p1 release];
//...

如果您不熟悉@property@synthesize我会recommend this article explaining both


为了响应编辑,您可以使用以下内容获取值:

Person *peep = [personArray objectAtIndex:i];
NSString *firstName = [peep firstName]; //or you could use peep.firstName;
NSString *lastName = [peep lastName];

答案 1 :(得分:1)

试试这个:

NSDictionary *person = [[NSDictionary alloc] initWithObjectsAndKeys:
                        @"Bill", @"Firstname", 
                        @"Gates", @"Lastname", nil];
NSMutableArray *storage = [[[NSMutableArray alloc] init] autorelease];
[storage addObject:person];
[person release];