0

I have defined the following interface:

@interface ListNode : Object
    {
    @private
    int value;
    ListNode* next;
    }

    - (id) value: (int) value_value; //Don't judge me, okay?
    - (int) value;
    - (id) next: (ListNode*) next_value;
    - (ListNode*) next;
@end

And the following implementation:

@implementation ListNode

    - (id) value: (int) value_value
    {
        value = value_value;
        return self;
    }

    - (int) value
    {
        return value;
    }
    - (id) next: (ListNode*) next_value
    {
        next = next_value;
        return self;
    }

    - (ListNode*) next
    {
        return next;
    }

@end

Then finally in my main method I am trying to do this:

ListNode *root;
root = [ListNode new];

When I compile the program I don't get any errors but I do get a warning that says: class method '+new' not found (return defaults to 'id') [-Wobjc-method-access]

I tried to run the program and I get a segfault and I can't figure out where it is. I looked up the wikibook on this and it had almost the exact same syntax as me so I don't understand what's wrong.

pkamb
  • 33,281
  • 23
  • 160
  • 191
sgmm
  • 580
  • 2
  • 7
  • 13

2 Answers2

1

There's 2 problems with your header file. I fixed your code and it works with foundation frame work. First there's no Object in Objective-C , you can inherit from NSObject instead and second you should use setter methods for assigning values to your properties :

@interface ListNode : NSObject
{
@private
    int value;
    ListNode* next;
}

- (id) setValue: (int) value_value;
- (int) value;
- (id) setNext: (ListNode*) next_value;
- (ListNode*) next;

@end

the class implementation:

#import "ListNode.h"

@implementation ListNode

- (id) setValue: (int) value_value
{
    value = value_value;
    return self;
}

- (int) value
{
    return value;
}
- (id) setNext: (ListNode*) next_value
{
    next = next_value;
    return self;
}

- (ListNode*) next
{
    return next;
}


@end

and as for the object instantiation you use alloc init and cause you have a setter you can just assign values:

//creating a root node
ListNode *root;
root = [[ListNode alloc] init];
root.value = 10;

//creating a node with no children
ListNode *child = [[ListNode alloc] init];
child.value = 20;
child.next = nil;

//assigning a child to root
root.next = child;

Hope that helps, you should look into object initializers and getter and setters for more info. You can look at this question: Please explain Getter and Setters in Objective C

Community
  • 1
  • 1
MKoosej
  • 3,405
  • 3
  • 21
  • 29
0

Your interface can be resumed to (Node.h):

#import <Foundation/Foundation.h>

@interface Node : NSObject

@property (strong, nonatomic) Node *next;
@property (strong, nonatomic) NSObject *value;

@end

If thats not for educational purposes, you should just stick with NSMutableArray or NSArray.

Diogo Martins
  • 917
  • 7
  • 15