Reputation:
Setup:
ViewController
holds an MyArray
of objects from the PersonClass
.
PersonClass
has just two properties: name
and age
.
Problem:
When I want to read out a name
property from the first object in MyArray
whats the proper way to do this?
Do I have to temporarily create an instance of PersonClass
like this?
PersonClass *tmp = [PersonClass alloc] init];
tmp = [MyArray objectAtIndex:0];
NSLog(@"%@", tmp.name);
Or can I refer directly to the properties
of the objects
in the MyArray
?
Something like this:
NSLog(@"%@", [self.contactsArray objectAtIndex:0].name); // not working
Upvotes: 1
Views: 2559
Reputation: 104718
if you want or need the type to be present, then introduce the type like so:
PersonClass * person = [array objectAtIndex:0];
i do this quite regularly for readability, and because included files' declarations can otherwise break things.
note that the cast is not required when assigning an objc variable from an id
value.
Do I have to temporarily create an instance of PersonClass?
No. The program you wrote creates a temporary which is never used.
Upvotes: 0
Reputation: 10333
I'd strongly advise using
[(PersonClass *)[MyArray objectAtIndex:0] name]
instead of seemingly cleaner, but troublesome form
[[MyArray objectAtIndex:0] name]
There are two reasons for this. First of all, it's explicit for the reader what gets called on which object. Secondly, it's explicit for the compiler - if two methods share the same name, but different return values things can get nasty. Matt Gallagher at Cocoa With Love has an excellent explanation of this issue.
Upvotes: 6
Reputation: 4286
Do I have to temporarily create an instance of PersonClass like this?
PersonClass *tmp = [PersonClass alloc] init]; tmp = [MyArray objectAtIndex:0]; NSLog(@"%@", tmp.name);
No. Just use
PersonClass *tmp = (PersonClass *)[myArray objectAtIndex:0];
NSLog(@"%@", tmp.name);
As the object you are getting from myArray is (or should be!) already alloc'd and init'd before being added to the array. The things in the array are pointers to objects. That's what you are passing around. You have to tell it which type of object you have in there though (the cast is (PersonClass *)
) because NSArray just stores NSObjects.
You could also do it in one line as thus
((PersonClass *)[myArray objectAtIndex:0]).name;
Upvotes: 0
Reputation: 21818
((PersonClass *)[MyArray objectAtIndex:0]).name
or just [[MyArray objectAtIndex:0] name]
Upvotes: 0
Reputation: 11340
You can do this
PersonClass *tmp = (PersonClass *) [MyArray objectAtIndex:0];
NSLog(@"%@",tmp.name);
Or we can put this on just one line:
NSLog(@"%@",((PersonClass *)[MyArray objectatIndex:0]).name);
The reason that NSLog(@"%@", [self.contactsArray objectAtIndex:0].name);
doesn't work is you haven't told the compiler what type of object is at [self.contactsArray objectAtIndex:0]
. Because it doesn't know what type of object is in your array, there is no way for it to know that it has a name
property
Upvotes: 0