简体   繁体   English

处理数组中的多个字符串和整数

[英]Handling Multiple Strings And Ints In An Array

I am trying to create an app in which I have an array(?) that holds the name and other information(2 strings, 3 ints) of the user. 我正在尝试创建一个应用程序,其中有一个包含用户名和其他信息(2个字符串,3个整数)的array(?)。 I also want the user to specify how many names the app can hold. 我还希望用户指定应用程序可以容纳多少个名称。

I was wondering exactly how would I do this? 我想知道我该怎么做? I was wondering if I can use a multidimensional array. 我想知道是否可以使用多维数组。

Thanks 谢谢

听起来您想要的是一个User类,其中包含每个用户具有的属性以及这些属性的数组。

You can use an NSMutableArray that contains NSDictionaries of the items. 您可以使用包含项目的NSDictionaries的NSMutableArray。

NSMutableArray *array = [NSMutableArray array];

NSString *name = @"Name ";
NSString *value1 = @"Value 1";
int       value2 = 2;
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                      name, @"name",
                      value1, @"value1Name",
                      [NSNumber numberWithInt:value2], @"value2Name",
                      nil];
[array addObject: dict];

// Create more dictioaries as there are more items and add them to the array //创建更多词典,因为有更多项目并将它们添加到数组中

As stated previously, your best bet would be to add a class to hold the information and then add each object into an NSArray (Here is an example): 如前所述,最好的选择是添加一个类来保存信息,然后将每个对象添加到NSArray中(这里是一个示例):

@interface User : NSObject
{
  NSString *string1;
  NSString *string2;
  int int1;
  int int2;
  int int3;
}

@property (nonatomic, retain) NSString *string1;
@property (nonatomic, retain) NSString *string2;
@property (nonatomic) int int1;
@property (nonatomic) int int2;
@property (nonatomic) int int3;

@end

@implementation User

@synthesize string1, string2, int1, int2, int3;

// Add init and dealloc methods here

@end

// creating objects somewhere else in the code
User *userObj1 = [[User alloc] init];
User *userObj2 = [[User alloc] init];
userObj1.string1 = @"User1";
userObj1.int1 = 7;

NSArray *arrayOfUserObjects = 
  [[NSArray alloc] initWithObjects: userObj1, userObj2, nil];
[userObj1 release];
[userObj2 release];

// do stuff with array with User Objects

Yeah, either a custom class or a dictionary. 是的,自定义类或词典。 Or instead of a dictionary you can have another array, if you prefer. 或者,如果您愿意,也可以使用另一个数组代替字典。 With NSArray you can have any other Objective-C object as elements, including other NSArrays, NSDictionarys, or objects of your own custom class. 使用NSArray可以将任何其他Objective-C对象作为元素,包括其他NSArrays,NSDictionary或您自己的自定义类的对象。 (You could do the same with an array of NSObject pointers, but NSArray nicely handles retains for you.) (您可以对一组NSObject指针执行相同的操作,但NSArray可以很好地为您处理保留。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM