Teo
Teo

Reputation: 3442

iOS create object

I want to create an object called Note . Then I want to assign some values to it's fields and display them in the console to verify that all of this works properly.

       Note.h
#import <Foundation/Foundation.h>

@interface Note : NSObject
{
    NSNumber *position;
    NSString *syllable;
}
@property(nonatomic, retain)NSNumber *position;
@property(nonatomic, retain)NSString *syllable;
@end

    Note.m

#import "Note.h"

@implementation Note
@dynamic position;
@dynamic syllable;
@end

After this , in another class I want to assign some values to the fields .

-(void) configNote:(Note*)not
{
    not = [Note alloc];
    [not setPosition:[NSNumber numberWithInt:2]];
    [not setSyllable:@"Twin-"];
}


.....
 Note *note;

 [self configNote:note];

 NSLog(@" pos : %d syl : %@ ",[[note position] integerValue],[note syllable]); 

I tried to use @synthesize instead of @dynamic but still nothing changes . The reason of the error is : -[Note setPosition:]: unrecognized selector sent to instance 0x733d060

Upvotes: 4

Views: 7241

Answers (4)

Stavash
Stavash

Reputation: 14294

If you are using ARC, try "strong" instead of "retain".

Upvotes: 0

kamprath
kamprath

Reputation: 2308

Your problem is that you are passing the Note object pointer to configNote: by value rather than by reference. Inside of configNote: when you set not to a newly allocated Note object, you are actually setting the local variable not to that value. What your NSLog call outside of your configNote: object actually receives is original note value prior to the call to configObject:.

To get what I believe you desire, either more the Note object allocation outside of the configObject: method, or pass the Note object pointer to configObject: by reference.

Upvotes: 0

Besi
Besi

Reputation: 22939

Since your question is quite basic and fundamental you might want to check out this Tutorial on cocoadevcentral. It's very well done and teaches you some of the basics when dealing with objects.

Upvotes: 2

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 39978

init your note and use custom init method to initialize ivars and change dynamic to synthesize and for better use this init to initialize your varibales

- (id)initWithPosition:(NSNumber*)pos andSyllable:(NSString*)syl {
    self = [super init];
    if (self) {
        self.position = pos;
        self.syllable= syl;
    }
    return self;
}

Upvotes: 4

Related Questions