Subclass access warnings in Objective-C

Apprentice
Posts: 5
Joined: 2009.09
Post: #1
Hi,

I am having some potential issues with my code where I am trying to use a getter in a subclass. Basically the code runs normally but I do get a warning during compilation. I am wondering if there is a better way to do this or do I just have to live with the warning.

Here is what is going on:

Superclass:

Code:
@interface SuperObject : NSObject
{
    NSString *name;
}

@property (nonatomic, assign) NSString *name;

@end

Subclass:

Code:
@interface SubObject : SuperObject
{
    int value;
}

@property (nonatomic, assign) int value;

@end

So if I create an array of SubObjects:

Code:
NSMutableArray *myArray = [[NSMutableArray alloc] init];

SubObject *sub;

sub = [[SubObject alloc] init];
[myArray addObject:sub];
[sub release];

sub = [[SubObject alloc] init]
[myArray addObject:sub];
[sub release];

And then I try to use that array:

Code:
for (SuperObject *obj in myArray)
{
    NSLog(@"Value %d", [obj value]);
}

When I compile this I get a warning saying "warning: no '-value' method found"

When I run it it works and does print out the right value...

Even if I change it to this:

Code:
for (SubObject *obj in myArray)
{
    NSLog(@"Value %d", [obj value]);
}

I still get the warning... Mad

Any insight would be greatly appreciated.

Best regards.
Quote this message in a reply
⌘-R in Chief
Posts: 1,261
Joined: 2002.05
Post: #2
SuperObject doesn't define -value, so calling -value on a SuperObject is going to give you a warning. That is a good and expected thing.

Solution? Either use the type "id" instead of SuperObject in that spot* or use SubObject.

You're using SubObject, but still getting the error. This pretty much guarantees that you forgot to #import "SubObject.h"


* If you use "id", you still need to have imported a header that contains a declaration for -value. -value also needs to be a unique selector for its param/return types otherwise you'll get a warning about multiple methods. If you get that, then you'll need to typecast the id reference to a concrete type to get rid of the warning anyway, so you'd just end up using SubObject anyway.
Quote this message in a reply
Apprentice
Posts: 5
Joined: 2009.09
Post: #3
Yes that was exactly it, the darn .h file wasn't being imported. Not sure why anything worked...

Thanks again.
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Subclass not replacing Superclass Sumaleth 2 3,476 Mar 21, 2010 08:37 PM
Last Post: Sumaleth
  Potentially faster array access in C++? imikedaman 7 5,619 Aug 5, 2006 10:09 AM
Last Post: aarku
  speeding up IO and memory access Atomical 3 3,085 Oct 10, 2005 05:04 PM
Last Post: Atomical