0

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?

3 Answers 3

2

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];
Sign up to request clarification or add additional context in comments.

Comments

1

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.

4 Comments

[self.messages objectAtIndex:indexPath.row].sender - is this closer to what I want? It's not picking up the sender property. Do I have to set it equal to a JSMessage object first and go from there?
The sender property thing is a different issue! objectAtIndex: returns an id, and an id has no sender property. You can assign or cast to a JSMessage; alternatively, use the method rather than the property, [[self.messages objectAtIndex:indexPath.row] sender].
Yup I just realized this. Late night coding, heh.
I discuss the dot-notation-with-id issue here (see the fifth paragraph, the one in parentheses): apeth.com/iOSBook/ch05.html#_properties
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.