Question

Yet another C#/.NET guy trying to learn Objective-C with big dreams of making millions with an iPhone app :)

Ok, I'm sure this question stems from me being so used to static typed languages, and therefore am having a tough time adjusting, but here's my issue. Let's assume I have a class called MyObect:

MyObject.h

@interface MyObject : NSObject
{

}

-(void)Foo;

@end

MyObject.m

#import "MyObject.h"
@implementation MyObject

-(void)Foo
{
  //do something fooey
}

@end

Now I'm trying to mess with an NSMutableArray of these objects, so in my main I fill an array of these objects something like this:

NSMutableArray *array = [[NSMutableArray alloc] init];
for(int i = 0; i<10;i++)
{
   MyObject *obj = [[MyObject alloc]init];
   [array addObject:obj];
}

Nothing fancy. Now, however, I was trying to pull out the first one of the array, and call the foo method. So, here's where I'm getting confused. I've tried this:

MyObject *obj = [array objectAtIndex:1];
[obj Foo];

and while this works, I get a warning of MyObject may not respond to message. So, I figured, ok, let me cast it:

MyObject *obj = (MyObject *)[array objectAtIndex:1];
[obj Foo];

and that also gives me the warning.

I guess my question is a fundamental question as to how you store items in a collection, and how you pull them out and still retain the object's type. Again, I'm coming from a .NET background, so maybe my thinking is fundamentally flawed, so if anyone can point me in the right direction, I'd greatly appreciate it.

EDIT: My original code did in fact have the asterisk in the cast (without it you get a compile error). It still shows the warning though...

Was it helpful?

Solution

This should not give a warning, given that you include the asterisk as you describe in a comment to another answer. In fact, I think the cast is unnecessary -- even the version without the cast should not give a warning.

Make sure that the header file MyObject.h is #imported at the start of the file where you are trying to call your method. The warning that you get is typical of cases where you have forward-declared a class with @class MyObject but not included the header with #import "MyObject.h".

BTW, in Objective-C one usually starts method names with a lowercase letter, as in Java.

OTHER TIPS

Change your casting line to:

MyObject *obj = (MyObject *)[array objectAtIndex:1];

The missing * is the problem.

OK, I feel like a total moron right now :( I forgot to add the method declaration to the header file. The fact that both of you kept stressing that I need to make sure I'm importing the header file, made me realize this. Thanks both of you for your help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top