Object—C基础

来源:互联网 发布:linux 路由跟踪 编辑:程序博客网 时间:2024/05/05 15:45
OC的整型表示 NSInteger
OC的浮点类型 CGFloat
OC的字符串前需要加@来区分C语言的字符串
方法的调用一般使用[指针  实例方法:传入参数…]的格式调用
‘.’方法的用法与限制:只有实现了get/set才可以在等号两边使用,如果只实现一种,则只能用在这种方法的情况上
自定义初始化
构造函数-(id)initWithxxx:(xxx)xx
{
self = [super init];
if( self != nil)
{
_xx = xx;

}
return self;
}
NSString转C语言格式字符串cString  OS X 10.4以上才有


如何去除NSlog的时间打印...

#define NSLog(FORMAT, ...) printf("%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String])

Car.m

#import "Car.h"@implementation Car-(id)initWithNameAndLicenceAndEngineAndLamp:(NSString*)name                                    Licence:(NSInteger)licence                                     Engine:(Engine*)engine                                       Lamp:(Lamp*)lamp;{    self = [super init];    if (self != nil) {        _name = name;        _licence = licence;        _engine = engine;        _lamp = lamp;    }    return self;}-(void)run;{    printf("在我面前的是车牌为%ld的%s的车,我把%s打着火,", _licence, [_name cString], [_name cString]);    [_engine turn];    [_lamp light];}-(void)stop;{    printf("到达目的地了,我停好%s车后,", [_name cString]);    [_engine stopTurn];    [_lamp dark];}@end

Engine.m

#import "Engine.h"@implementation Engine-(void)setModel:(NSString*)model;{    _model = model;}-(NSString*)model;{    return _model;}-(void)setCapacity:(NSInteger)capacity;{    _capacity = capacity;}-(NSInteger)capacity;{    return _capacity;}-(void)turn;{    NSLog(@"达到%ld排量的%@型号的引擎发出令人沉醉的轰鸣。", _capacity, _model);}-(void)stopTurn;{    NSLog(@"引擎渐渐停止了转动,一切变得安静了下来。");}@end

Lamp.m

#import "Lamp.h"@implementation Lamp-(void)setWatt:(NSInteger)watt;{    _watt = watt;}-(NSInteger)watt;{    return _watt;}-(void)light;{    NSLog(@"打开了%ld瓦的车灯!一束光照亮了前方。", _watt);}-(void)dark;{    NSLog(@"关闭了%ld瓦的车灯!", _watt);}@end
main.m

#import <Foundation/Foundation.h>#import "Car.h"#import <unistd.h>int main(int argc, const char * argv[]){    Engine* engine = [[ Engine alloc]init];    engine.model = @"EcoBoost 1.0T GTDi";    engine.capacity = 1600;    Lamp* lamp = [[Lamp alloc]init];    [lamp setWatt:200];    Car* haoche = [[Car alloc]initWithNameAndLicenceAndEngineAndLamp:@"Ferrari"                                                             Licence:888888                                                              Engine:engine                                                                Lamp:lamp];    [haoche run];    for ( int i = 3; i > 0; --i) {        switch (i) {            case 3:                NSLog(@"经过漫长的驾驶.");                break;            case 2:                NSLog(@"经过漫长的驾驶..");                break;            case 1:                NSLog(@"经过漫长的驾驶...");                break;            default:                break;        }        sleep(1);    }        [haoche stop];    return 0;}



0 0
原创粉丝点击