Dalibor
Dalibor

Reputation: 163

How to call a method from an object in an array?

I'm new to Objective-c and I think this should be really easy but somehow I can't figure it out.

I need to call a method from an object which is stored in an NSArray. The Java code would be: myArray[0].getMyValue();

So I read on the internet that in Objective-c it should look like this: [[myArray objectAtIndex: 0] getMyValue]. Unfortunately this didn't work.

I found other solutions on the internet but none of them worked.

So I hope you guys could help me out?

Update

I'm getting these two error messages:

Upvotes: 2

Views: 118

Answers (2)

Dominik Hadl
Dominik Hadl

Reputation: 3619

This doesn't work because Objective-C doesn't know what is the type of the object in the array.

Luckily, Apple has added lightweight generics in Xcode 7, which allow you to create typed arrays. This will of course work only if you intend to have one type of object in the array. The syntax looks like this:

NSArray<NSString *> *stringArray;

If you plan to have objects with different types in the array, then you need to cast the object to your type, to be able to call your method. That would look like this:

[((YourObject *)[myArray objectAtIndex: 0]) getMyValue];

And as @Michael pointed out in the comment, another and nicer way to do this would be:

[((YourObject *)myArray[0]) getMyValue];

Upvotes: 7

Randy
Randy

Reputation: 4525

Objects are stored with id type in NSArray, so you can cast this object to the object type you want. For instance :

NSNumber *myNumber = (NSNumber *)[NSArray objectAtIndex:0];
[myNumber myMethod];

Upvotes: 3

Related Questions