开发者

Handling Multiple Strings And Ints In An Array

开发者 https://www.devze.com 2023-04-07 00:32 出处:网络
I am t开发者_如何学运维rying to create an app in which I have an array(?) that holds the name and other information(2 strings, 3 ints) of the user. I also want the user to specify how many names the a

I am t开发者_如何学运维rying to create an app in which I have an array(?) that holds the name and other information(2 strings, 3 ints) of the user. 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


Sounds like what you'd want is a User class, with the properties each user has, and an array of those.


You can use an NSMutableArray that contains NSDictionaries of the items.

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):

@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. (You could do the same with an array of NSObject pointers, but NSArray nicely handles retains for you.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号