简体   繁体   中英

objective-c object or classes

I'm new in objective-c I used to code with java.

I wrote the code below in Xcode 4.5

The code must get me this output:

 the value of  m is:
  1/3

but I get this output :

the value of  m is:

if can anyone tell me what is wrong in the code

the code :

#import <Foundation/Foundation.h>

@interface Fraction : NSObject
{
    int num ;
    int dem;
}

-(void) print;
-(void) setNum:(int) n ;
-(void) setDem: (int) d;
@end


@implementation Fraction
-(void) print {
    NSLog(@"%i/%i",num,dem);
}
-(void) setNum:(int)n{

    num=n;
    NSLog(@"set num work fine %i:",n);
}

-(void)setDem:(int)d{
    dem=d;
    NSLog(@"set dem work fine %i:",d);
}

@end

int main (int argc ,char *argv[]){

    @autoreleasepool {
        Fraction *m;

        // m=[m alloc] ;
        m=[m init];

        [m setNum:1];
        [m setDem:3];

        NSLog(@"the value of  m is:");
        [m print];
    }return 0;

}

can anyone explain m=[m alloc] ; in the new xcode

alloc is a class method, so you have to call it on your class:

m = [[Fraction alloc] init];

or, with your style:

m = [Fraction alloc];
m = [m init];

This is the reason for which you don't print anything, m is still nil since you didn't alloc it. Sending the init message to a nil receiver returns nil , so you basically have a nil object when you try to print.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM