使用NSArray初始化对象数组

时间:2021-10-23 16:59:57

I'm pretty new to Objective-C and iOS so I've been playing around with the Picker View. I've defined a Person Class so that when you create a new Person it automatically gives that person a name and age.

我是Objective-C和iOS的新手所以我一直在玩Picker视图。我定义了Person类,当你创建一个新的Person时,它会自动地给这个Person一个名称和年龄。

#import "Person.h"

@implementation Person

@synthesize personName, age;

-(id)init
{
    self = [super init];
    if(self)
    {
        personName = [self randomName];
        age = [self randomAge];
    }

    return self;
}

-(NSString *) randomName
{
    NSString* name;
    NSArray* nameArr = [NSArray arrayWithObjects: @"Jill Valentine", @"Peter Griffin", @"Meg Griffin", @"Jack Lolwut",
                            @"Mike Roflcoptor", @"Cindy Woods", @"Jessica Windmill", @"Alexander The Great",
                            @"Sarah Peterson", @"Scott Scottland", @"Geoff Fanta", @"Amanda Pope", @"Michael Meyers",
                            @"Richard Biggus", @"Montey Python", @"Mike Wut", @"Fake Person", @"Chair",
                            nil];
    NSUInteger randomIndex = arc4random() % [nameArr count];
    name = [nameArr objectAtIndex: randomIndex];
    return name;
}

-(NSInteger *) randomAge
{
    //lowerBound + arc4random() % (upperBound - lowerBound);
    NSInteger* num = (NSInteger*)(1 + arc4random() % (99 - 1));

    return num;
}

@end

Now I want to make an array of Persons so I can throw a bunch into the picker, pick one Person and show their age. First though I need to make an array of Persons. How do I make an array of objects, initialize and allocate them?

现在我想要创建一个人的数组,这样我就可以把一串人放入挑选器中,选择一个人并显示他们的年龄。首先,我需要找一堆人。如何创建对象数组,初始化并分配它们?

4 个解决方案

#1


38  

NSMutableArray *persons = [NSMutableArray array];
for (int i = 0; i < myPersonsCount; i++) {
   [persons addObject:[[Person alloc] init]];
}
NSArray *arrayOfPersons = [NSArray arrayWithArray:persons]; // if you want immutable array

also you can reach this without using NSMutableArray:

你也可以使用NSMutableArray:

NSArray *persons = [NSArray array];
for (int i = 0; i < myPersonsCount; i++) {
   persons = [persons arrayByAddingObject:[[Person alloc] init]];
}

One more thing - it's valid for ARC enabled environment, if you going to use it without ARC don't forget to add autoreleased objects into array!

还有一件事——它对于启用了ARC的环境是有效的,如果你要使用它而不使用ARC,不要忘记在数组中添加autoreleated对象!

[persons addObject:[[[Person alloc] init] autorelease];

#2


69  

There is also a shorthand of doing this:

也有一种简写:

NSArray *persons = @[person1, person2, person3];

It's equivalent to

它等于

NSArray *persons = [NSArray arrayWithObjects:person1, person2, person3, nil];

As iiFreeman said, you still need to do proper memory management if you're not using ARC.

正如iiFreeman所说,如果不使用ARC,仍然需要进行适当的内存管理。

#3


9  

No one commenting on the randomAge method?

没有人对随机方法发表评论?

This is so awfully wrong, it couldn't be any wronger.

这是如此严重的错误,不可能有任何错误。

NSInteger is a primitive type - it is most likely typedef'd as int or long. In the randomAge method, you calculate a number from about 1 to 98.

NSInteger是一种原始类型——它很可能是int型或long型。在随机方法中,你计算一个数字,从1到98。

Then you can cast that number to an NSNumber. You had to add a cast because the compiler gave you a warning that you didn't understand. That made the warning go away, but left you with an awful bug: That number was forced to be a pointer, so now you have a pointer to an integer somewhere in the first 100 bytes of memory.

然后可以将这个数字转换为NSNumber。您必须添加一个强制转换,因为编译器给您一个您不理解的警告。这使得警告消失了,但是给您留下了一个可怕的错误:这个数字必须是一个指针,所以现在您有一个指向前100个字节内某个整数的指针。

If you access an NSInteger through the pointer, your program will crash. If you write through the pointer, your program will crash. If you put it into an array or dictionary, your program will crash.

如果您通过指针访问一个NSInteger,您的程序将会崩溃。如果您通过指针写入,您的程序将崩溃。如果您将它放入数组或字典,您的程序将崩溃。

Change it either to NSInteger or int, which is probably the best, or to NSNumber if you need an object for some reason. Then create the object by calling [NSNumber numberWithInteger:99] or whatever number you want.

将它改为NSInteger或int,这可能是最好的,如果出于某种原因需要对象,则将它改为NSNumber。然后通过调用[NSNumber withinteger:99]或任何您想要的数字来创建对象。

#4


-1  

This way you can Create NSArray, NSMutableArray.

这样可以创建NSArray, NSMutableArray。

NSArray keys =[NSArray arrayWithObjects:@"key1",@"key2",@"key3",nil];

NSArray objects =[NSArray arrayWithObjects:@"value1",@"value2",@"value3",nil];

#1


38  

NSMutableArray *persons = [NSMutableArray array];
for (int i = 0; i < myPersonsCount; i++) {
   [persons addObject:[[Person alloc] init]];
}
NSArray *arrayOfPersons = [NSArray arrayWithArray:persons]; // if you want immutable array

also you can reach this without using NSMutableArray:

你也可以使用NSMutableArray:

NSArray *persons = [NSArray array];
for (int i = 0; i < myPersonsCount; i++) {
   persons = [persons arrayByAddingObject:[[Person alloc] init]];
}

One more thing - it's valid for ARC enabled environment, if you going to use it without ARC don't forget to add autoreleased objects into array!

还有一件事——它对于启用了ARC的环境是有效的,如果你要使用它而不使用ARC,不要忘记在数组中添加autoreleated对象!

[persons addObject:[[[Person alloc] init] autorelease];

#2


69  

There is also a shorthand of doing this:

也有一种简写:

NSArray *persons = @[person1, person2, person3];

It's equivalent to

它等于

NSArray *persons = [NSArray arrayWithObjects:person1, person2, person3, nil];

As iiFreeman said, you still need to do proper memory management if you're not using ARC.

正如iiFreeman所说,如果不使用ARC,仍然需要进行适当的内存管理。

#3


9  

No one commenting on the randomAge method?

没有人对随机方法发表评论?

This is so awfully wrong, it couldn't be any wronger.

这是如此严重的错误,不可能有任何错误。

NSInteger is a primitive type - it is most likely typedef'd as int or long. In the randomAge method, you calculate a number from about 1 to 98.

NSInteger是一种原始类型——它很可能是int型或long型。在随机方法中,你计算一个数字,从1到98。

Then you can cast that number to an NSNumber. You had to add a cast because the compiler gave you a warning that you didn't understand. That made the warning go away, but left you with an awful bug: That number was forced to be a pointer, so now you have a pointer to an integer somewhere in the first 100 bytes of memory.

然后可以将这个数字转换为NSNumber。您必须添加一个强制转换,因为编译器给您一个您不理解的警告。这使得警告消失了,但是给您留下了一个可怕的错误:这个数字必须是一个指针,所以现在您有一个指向前100个字节内某个整数的指针。

If you access an NSInteger through the pointer, your program will crash. If you write through the pointer, your program will crash. If you put it into an array or dictionary, your program will crash.

如果您通过指针访问一个NSInteger,您的程序将会崩溃。如果您通过指针写入,您的程序将崩溃。如果您将它放入数组或字典,您的程序将崩溃。

Change it either to NSInteger or int, which is probably the best, or to NSNumber if you need an object for some reason. Then create the object by calling [NSNumber numberWithInteger:99] or whatever number you want.

将它改为NSInteger或int,这可能是最好的,如果出于某种原因需要对象,则将它改为NSNumber。然后通过调用[NSNumber withinteger:99]或任何您想要的数字来创建对象。

#4


-1  

This way you can Create NSArray, NSMutableArray.

这样可以创建NSArray, NSMutableArray。

NSArray keys =[NSArray arrayWithObjects:@"key1",@"key2",@"key3",nil];

NSArray objects =[NSArray arrayWithObjects:@"value1",@"value2",@"value3",nil];