xcode4.2
建项目的时候要选 foundation,不然没有Foundation包
注意看,这里不在需要手动写setUserName
要得到属性值的话,用self.****
main.m
#import <Foundation/Foundation.h> #import "Fraction.h" int main (int argc, const char * argv[]) { @autoreleasepool { // insert code here... //NSLog(@"Hello, World!"); // insert code here... printf("Hello, World!\n"); Fraction *frac = [[Fraction alloc] init]; // set the values [frac setUserName: @"mahone"]; //[frac setDenominator: 3]; // print it printf( "The fraction is: " ); [frac print]; } return 0; }
Fraction.h
#import <Foundation/Foundation.h> @interface Fraction : NSObject { //NSInteger *numerator; //NSInteger *denominator; NSString *userName; } -(void) print; /* -(void) setNumerator: (int) d; -(void) setDenominator: (int) d; -(int) numerator; -(int) denominator; */ //@property (nonatomic, copy) NSInteger *numerator; @property (nonatomic, copy) NSString *userName; @end
Fraction.m
#import "Fraction.h" #import <stdio.h> @implementation Fraction /* -(void) print { printf( "%i/%i", numerator, denominator ); } -(void) setNumerator: (int) n { numerator = n; } -(void) setDenominator: (int) d { denominator = d; } -(int) denominator { return denominator; } -(int) numerator { return numerator; } */ @synthesize userName = _userName; -(void) print { NSString *nameString = self.userName; if (nameString.length == 0) { nameString = @"World"; } NSString *greeting = [[NSString alloc] initWithFormat:@"Hello, %@!", nameString]; //NSLog(@"Hello, %@",nameString); printf("%s\n" , [greeting UTF8String]); } @end