2

I'm pretty new to programming, and am a little caught up in what to do. Now, each of the objects in my NSArray has its own properties containing data in which I need. I'm used to iterating through an array to access it's objects, but have never had to iterate through one and access the properties of some of its objects. So I am completely lost.

Usually when I need to iterate through an array, it's a straightforward process, something like:

For (int i =0; i <= self.array.count; i++) {
NSLog(@"%d", i):
}

Easy enough. But, now I'm faced with the challenge of looking into the all jacked stored in the arrays index, and access a piece of information from that given object. I need to do this and a for loop since there are multiple objects. I believe from what I've read on this website that I have the logic behind it correct, but I am unsure of how to access the object's properties rather than just the object itself.

Henry F
  • 4,960
  • 11
  • 55
  • 98

2 Answers2

2

When you say:

for (int i = 0; i <= self.array.count; i++) {
    // ... inside the loop ...
}

...then when you are inside the loop, each object in the array can be obtained, one per iteration, as [self.array objectAtIndex:i]. So fetch that. Now you have one of your objects!

Now just access any property of that object you like. You will probably want to cast to the correct type of that object, so that the compiler understands what sort of object this is and will allow you to do whatever it is you want to do.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 1
    Objective-C has a more compact way of iterating through an NSArray, as Josh rightly points out, but I used your notation so as to start in the place where you have started. – matt May 21 '15 at 23:59
  • The cast remark is an important point, since you can't use dot notation on an `id`, which is the return type of `objectAtIndex:` – jscs May 22 '15 at 00:08
1

Use fast enumeration instead of iteration by index, and then access the property as usual.

for( id obj in myArray ){    // Use a more specific type than id if possible
    NSLog(@"%@", [obj prop]);
}

Another option is to use Block-based enumeration. There, you will write a Block one of whose arguments is an object from your array. (The objects are presented to the Block in order.)

[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL * stop){
    NSLog(@"%@", [obj prop]);
}];

In this case, you also have access to the index if you need it for some reason. The stop argument allows early termination of the loop if you need that.

Community
  • 1
  • 1
jscs
  • 63,694
  • 13
  • 151
  • 195