Objective-C程序设计第三章:类,对象和方法

这一章简单介绍了如何书写Objective-C的类,对象和方法

类的声明:

@interface Computer: NSObject
使用interface关键字,而不是传统面向对象的class。

在头文件中声明类,向其中加入方法和属性。

实例方法用 - 开头 

类方法用 + 开头

俩个方法的区别:

1.类别符号不同

2.实例方法可以用实例变量, 类方法不可以用实例变量

#import <Foundation/Foundation.h>

@interface Computer : NSObject

{
    NSString *kaka;
    int number;
}

- (void)setDoc: (NSString *)docContent;

- (void)printDoc;

- (NSString *)getDoc;

- (void)setMovie: (NSString *)movieName;

- (NSString *)getMovie;

- (void)playMovie;

+ (void)helloComputer;

@end

类的定义(又叫实现):

#import "Computer.h"

@implementation Computer
{
    NSString *doc;
    NSString *movie;
}

- (void)setDoc: (NSString *)docContent{
    doc = docContent;
}

- (void)printDoc{
    NSLog(@"The doc %@ is printing...", doc);
}

- (NSString *)getDoc{
    return doc;
}

- (void)setMovie: (NSString *)movieName{
    movie = movieName;
}

- (NSString *)getMovie{
    return movie;
}

- (void)playMovie{
    NSLog(@"We are watching movie %@", movie);
}

+ (void)helloComputer{
    NSLog(@"Computer say 'hello' to you");
}

@end


为什么要有setter, getter方法?

因为无法直接访问类的实例变量。


类的创建和方法调用:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        [Computer helloComputer];
        
        Computer *computer = [[Computer alloc] init];
        
        [computer setDoc:@"真好玩"];
        
        //[computer printDoc];
        NSLog(@"I'm printing the doc %@", [computer getDoc]);
        
        [computer setMovie:@"异形大战铁血战士"];
        
//        [computer playMovie];
        NSLog(@"I'm watch movie %@", [computer getMovie]);
        
        
    }
    return 0;
}


实例创建:类名 *实例 = [[类名 alloc] init];

类名 *实例 创建一个指针

[类名 alloc] 分配空间, init初始化内存空间

使用[实例名 方法名:参数]的方式调用实例方法。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值