第一个OC类的实现

17-12-15 15:07 字数 1438 阅读 2529 已编辑
#import <Foundation/Foundation.h>  
// 1.类的声明 @interface 类名 @end结尾  
// 类名的首字母必须大写  
@interface Iphone : NSObject  
{  
    // 属性  
    // 类的属性默认是protect修饰的  
    @public  
    float _model;// _开头  
    int _cpu;  
    double _size;  
    int _color;  
}  
// 方法  
// 没有参数不用写() 直接写; 因为()是用来扩住数据类型的  
// OC 中类方法用 + 表示(只能类调用) 对象方法用 - 表示(只能对象调用)  
- (void)about;  
- (char *)loadMessage;  
// OC中有参数要在数据类型前加 :  
// :是方法名称的一部分  
- (int)callPhone:(int)number;  
- (int)sendMessage:(int)number :(char *) content;  
// 为了提高代码阅读性,OC允许给每个参数添加标签  
- (int)sendMessageWithNumber:(int)number andContent:(char *) content;  
@end  

// 2.类的实现  
@implementation Iphone  
- (void)about {  
    NSLog(@"型号: %f, cpu: %d, 尺寸: %f, 颜色: %i", _model, _cpu, _size, _color);  
}  
-(char *)loadMessage {  
    return "电话已欠费,请及时缴费。";  
}  
- (int)callPhone:(int)number {  
    NSLog(@"打电话给%i", number);  
    return 1;  
}  
- (int)sendMessage:(int)number :(char *) content {  
    NSLog(@"发短信给%i,内容%s", number, content);  
    return 1;  
}  
- (int)sendMessageWithNumber:(int)number andContent:(char *) content {  
    NSLog(@"发短信给%i,内容%s", number, content);  
    return 1;  
}  
@end  

int main(int argc, const char * argv[]) {  
    // 通过类创建对象  
    // 在oc中要通过类创建对象 必须给类发送一个消息(好比c语言中调用方法)  
    // 发送消息 在OC中要发送消息先写[类名/对象名 方法名称];  

    // 调用new方法后会做三件事  
    // 1.给对象分配内存空间  
    // 2.初始化对象属性  
    // 3.返回对象地址  

    // 通过一个Iphone类型的指针接受Iphone对象的地址  
    Iphone *p = [Iphone new];  
    // p 即为Iphone对象  
    // oc中的类本质是结构体  
    p->_size = 4.5;  
    p->_model = 7;  
    p->_cpu = 10;  
    p->_color = 2;  
    // 打印对象属性  
    NSLog(@"color = %d, model = %f,size = %lf, cpu=%d", p->_color, p->_model, p->_size, p->_cpu);  
    // 调用对象方法  
    [p about];  
    char *content = [p loadMessage];  
    NSLog(@"content = %s", content);  
    [p callPhone:159011053];  
    [p sendMessage:122331 :"hello world"];  
    [p sendMessageWithNumber:12132131 andContent:"good luck"];  
    return 0;  
}  

这些- + [] 真是反人类啊

0人点赞>
关注 收藏 改进 举报
0 条评论
排序方式 时间 投票
快来抢占一楼吧
请登录后发表评论
站长 @ 十七度
文章
380
粉丝
23
喜欢
190
收藏
31
排名 : 1
访问 : 127.94万
私信