iphone - 数组对象的属性(Objective-c)

标签 iphone objective-c arrays object properties

我有一个 NSObject 类,它的名字是 test.
test 类有 3 个属性。 姓名, 年龄, id;
我在测试课上有 3 个对象。 s, b, c.
我将所有对象放入数组:NSArray *ary = [NSArray arrayWithObjects:@"a", @"b", @"c", nil];
我正在尝试访问该数组中的属性数据。这意味着我必须在循环(for 循环或 while 循环)中读取、写入数组中对象的属性。
我在网上找了很多资料。我接近做的方法是:

[[ary objectAtIndex:0] setName:@"example"];

此方法适用于 setter 和 getter。但它确实给出了一个可怕的错误。有什么“可行”的方法吗?
谢谢...

最佳答案

让我们想象一个 Person 类:

@interface Person : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic) NSInteger age;
@property (nonatomic) long long identifier;

+ (instancetype)personWithName:(NSString *)name age:(NSInteger)age identifier:(long long)identifier;

@end

@implementation Person

+ (instancetype)personWithName:(NSString *)name age:(NSInteger)age identifier:(long long)identifier {
    Person *person = [[self alloc] init];
    person.name = name;
    person.age = age;
    person.identifier = identifier;

    return person;
}

@end

然后你可以像这样创建一组人:

NSArray *people = @[[Person personWithName:@"Rob" age:32 identifier:2452323],
                    [Person personWithName:@"Rachel" age:29 identifier:84583435],
                    [Person personWithName:@"Charlie" age:4 identifier:389433]];

然后您可以像这样提取一组人名:

NSArray *names = [people valueForKey:@"name"];
NSLog(@"%@", names);

这将产生:

2013-09-27 14:57:13.791 MyApp[33198:a0b] (
    Rob,
    Rachel,
    Charlie
)

如果你想提取关于第二个Person的信息,那就是:

Person *person = people[1];
NSString *name = person.name;
NSInteger age = person.age;
long long identifier = person.identifier;

如果你想改变第三人称的年龄,那就是:

Person *person = people[2];
person.age = 5;

或者,如果您想遍历数组以提取信息,您也可以这样做:

for (Person *person in people) {
    NSString *name = person.name;
    NSInteger age = person.age;
    long long identifier = person.identifier;

    // now do whatever you want with name, age, and identifier
}

关于iphone - 数组对象的属性(Objective-c),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19057544/

相关文章:

c - 如何在 C 的二维字符数组中填充字符串?

C++ 列表显示表中的最后 3 个项目

iphone - iPhone 上 SMS 中嵌入的自定义 URL 方案

iphone - 如何将附加阴影添加到 uinavigationbar 和 uitoolbar

iphone - 重新加载自己创建的 UITableViewCell

objective-c - 如何使用 UIScrollView 和 CATiledLayer 在可缩放的 UIView 上绘制标记

ios - 我该怎么办 : [obj isKindOfClass:[Class class]]

iphone - 了解 Objective-C 中的协议(protocol)继承

ios - 我可以将两个按钮分配给 Xcode 7 中的同一个 Action 或 socket 吗?

c - 当我在 C 中 malloc 另一个字符串时,字符串发生变化