oe a
oe a

Reputation: 2280

Get property from object in array

I am having trouble getting an NSString property from an array. I have an NSArray composed of an object called JSMessage. Inside of this object is a string called sender I am trying to retrieve. At the moment, I am only trying to print it to the log. Here is the code I am trying:

NSLog(@"%@",[[self.messages [objectAtIndex:indexPath.row]].sender ]);

I get an error about my brackets and another one telling me objectAtIndex is an undeclared identifier.

What am I doing wrong?

Upvotes: 0

Views: 84

Answers (3)

rmaddy
rmaddy

Reputation: 318944

Besides removing all of the extra brackets, you can also do the following:

NSLog(@"%@", [self.messages[indexPath.row] sender]);

This uses the modern syntax for accessing elements from an NSArray. And since the array access returns an object of type id, you can't directly access the object's property using property syntax. You need to call the getter method as I show above.

Upvotes: 0

Lie-An
Lie-An

Reputation: 2563

It should be [self.messages objectAtIndex:indexPath.row]

From here you can see the object in a certain index.

To get the JSMessage object:

JSMessage *jSMessageObj = [self.messages objectAtIndex:indexPath.row];

Upvotes: 2

matt
matt

Reputation: 536027

Well, think about it. Your code contains the phrase [objectAtIndex. But a method name can never be the first thing in square brackets. The first thing in square brackets must be the receiver to which the message is being sent.

For example, you say [myString lowercaseString]. You don't say [lowercaseString]. But that is what you are saying.

Upvotes: 1

Related Questions