3

I have a NSObject class which's name is test.
class test has 3 property. Name, age, id;
I have 3 Objects in test class. s, b, c.
I am putting all of the objects to the array with: NSArray *ary = [NSArray arrayWithObjects:@"a", @"b", @"c", nil];
I am trying to access to the data of property in that array. Which means I have to read, write the property of the object in array in the loop (for loop or while loop).
I found a lot of materials on the internet. The method that I was close to do was:

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

This method was working with setters and getters. But it did give a horrible error. Is there any "WORKING" method to do it?
Thanks...

4

2 回答 2

13

让我们想象一个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
)

如果你想提取关于 second 的信息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
}
于 2013-09-27T18:58:55.887 回答
1

尝试这个

第 1 步:首先将其转换为适当的对象类型

s *myS = (s *)[array objectAtIndex:0];
b *myB = (b *)[array objectAtIndex:1]; 
c *myC = (c *)[array objectAtIndex:2]; 

第 2 步:设置/获取您想要的任何属性

myS.name = @"example";
于 2013-09-27T18:32:42.043 回答