在Objective-C中创建一个对象数组。 [英] Making an array of Objects in Objective-C.

查看:165
本文介绍了在Objective-C中创建一个对象数组。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在已经和XCode玩了大约两个星期,并且稍微阅读了MVC。我在尝试将模型连接到Controller时遇到问题,因为我发现很难理解数组。当我用Java编程时,我可以处理简单的数组但是我很安静地被Obj-C NSArrays 吓到了。

Been playing around with XCode for about 2 weeks now, and reading about MVC a bit. I have a problem trying to connect the Model to the Controller because I find it hard to get my head around arrays. I can handle simple arrays when i programmed some in Java but I'm quiet intimidated by the Obj-C NSArrays I see.

如果有人愿意向我展示一些对象的简单调用,我将永远感激。

If somebody would be so kind to show me some simple calls on an array of objects i would be eternally grateful.

我的模特:

Person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject 
{
NSString *name;
NSNumber *age;
}

@property(nonatomic, retain) NSString *name;
@property(nonatomic, retain) NSNumber *age;

@end

Person.m

#import "Person.h"
@implementation Person
@synthesize name;
@synthesize age;
@end

在我尝试学习的过程中,我保持非常简单。

I've kept if very simple while I try and learn.

现在是我的Controller类。我想要做的是创建一个包含40个人物对象的数组。但是我不知道将它放在Obj C的代码中的正确方法。

Now my Controller class. What i want to do is create an array of 40 'Person' objects. But i don't know the correct way to put that in code in Obj C.

Controller.h

Controller.h

#import <Foundation/Foundation.h>
@class Person;
@interface Controller : NSObject 
{
Person *person;
}
@property(nonatomic, retain) Person *person;

-(void) doSomeWork;

@end

Controller.m

Controller.m

#import "Controller.h"
#import "Person.h"

@implementation Controller

@synthesize person;


-(IBAction)doSomeWork
{
// I guess here is where i should create my array of 40 person objects
}

@end

我的问题是如何声明大小的人物对象数组40.
然后如何访问数组以读取和写入。

My problem is in how to declare the array of person objects of size 40. And then how to access the array to read and write to it.

提前感谢您阅读我的帖子。

Thanks in advance for reading my post.

推荐答案

这是一个在Controller类中创建NSMutableArray实例变量的示例,每次唤起doSomeWork时都会向该数组添加一个Person对象:

Here is an example that creates an NSMutableArray instance variable in the Controller class and adds a Person object to that array each time you evoke doSomeWork:

@interface Controller

NSMutableArray *personArray;

@end
@implementation Controller

- (void) viewDidLoad {
    ................
    NSMutableArray *personsArray = [[NSMutableArray alloc] initWithCapacity:40];
}

- (IBAction)doSomeWork {
    Person *myPerson = [[Person alloc] init];
    myPerson.name = name;
    myPerson.age = age;

    [personsArray addObject:myPerson];
}
@end

这篇关于在Objective-C中创建一个对象数组。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆