Objective-C class for working with fractions -


i'm trying learn programming, , language chose start objective c! i'm studying : programing in objective-c fourth edition, , bit stuck @ classes chapter.

we have following code :

#import <foundation/foundation.h>  @interface fraction: nsobject;  -(void) print; -(void) setnumerator: (int) n; -(void) setdenominator: (int) d;  @end  @implementation fraction {     int numerator;     int denominator;             }  -(void) print     {     nslog(@"%i/%i" , numerator, denominator); }  -(void) setnumerator:(int)n {     numerator = n;  }  -(void) setdenominator:(int)d {     denominator = d; } @end  int main (int argc, char * argv[]) {     @autoreleasepool {         fraction *myfraction;          myfraction = [fraction alloc];         myfraction = [fraction init];          [myfraction setdenominator:1];         [myfraction setnumerator:3];          nslog(@"the value of myfraction :");         [myfraction print];     }     return 0;  } 

i copied code book, in hopes me understand better, reason when try run following message :

2014-04-25 22:23:28.374 cocoterminal[1751:303] *** terminating app due uncaught exception 'nsinvalidargumentexception', reason: '*** +[fraction<0x1000011d8> init]: cannot init class object.' *** first throw call stack: (     0   corefoundation                      0x00007fff8f5a825c __exceptionpreprocess + 172     1   libobjc.a.dylib                     0x00007fff86403e75 objc_exception_throw + 43     2   corefoundation                      0x00007fff8f5ab490 +[nsobject(nsobject) dealloc] + 0     3   cocoterminal                        0x0000000100000dde main + 110     4   libdyld.dylib                       0x00007fff8d43a5fd start + 1 ) libc++abi.dylib: terminating uncaught exception of type nsexception (lldb)  

if kind explain , why causing error, complete noob forever grateful !

this line:

myfraction = [fraction init]; 

is giving rise cannot init class object exception. should be:

myfraction = [myfraction init]; 

you send alloc messages classes, init messages instances of classes. can't send init class object, error states. sending alloc class gives instance of class, , instance should sending init to.

as others have said, combining 2 lines fraction * myfraction = [[fraction alloc] init]; more usual way of doing it, way you're doing not wrong, once send init message correct thing.


Comments

Popular posts from this blog

How to access named pipes using JavaScript in Firefox add-on? -

multithreading - OPAL (Open Phone Abstraction Library) Transport not terminated when reattaching thread? -

node.js - req param returns an empty array -