Objective-C学习笔记-自定义类

1.OC中一个类由.h文件和.m文件组成,.h文件负责声明接口,.m文件负责具体实现

2.在.h文件中@interface后面的格式为类名:基类名

3.成员变量需要写在大括号内,最好使用下划线开头,使用成员变量需要写存取方法,为了开发效率,目前推荐使用属性代替成员变量,属性会自动生成带下划线的成员变量以及存取方法,还可以通过readonly,readwrite等来控制属性特性

4.成员方法以减号开头,静态成员方法以加号开头,参数类型以及返回值类型需要用括号括起来

5.可以通过重写description方法,让%@能描述自身

6.OC中self代表自己,super代表调用父类方法

7.在.m文件中可以使用@interface声明一些对外不可见的成员变量和成员方法

8.OC中可以通过@public @private @protecte等修饰成员变量,但是不能修饰成员方法

#import <Foundation/Foundation.h>

@interface MyDesktop : NSObject
{
    @public
    int _weight;
    int _height;
}
-(int)height;
-(void)setHeight:(int)h;
-(int)weight;
-(void)setWeight:(int)w;
-(void)setCustomSize:(int)newSize;

+(void)sayHello;

@property(nonatomic,readonly) int size;
@end
#import "MyDesktop.h"
//类扩展
@interface MyDesktop()
@property(nonatomic)int childCount;
@property(nonatomic,readwrite) int size;
@end

@implementation MyDesktop

- (int)height{
    return _height;
}

- (void)setHeight:(int)h{
    _height=h;
}

- (int)weight{
    return _weight;
}

- (void)setWeight:(int)w{
    _weight=w;
}

-(void)setCustomSize:(int) newSize{
    self.size=newSize;
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"height=%d,weight=%d,size=%d,childcount=%d", _height,_weight,_size,_childCount];
}

+(void)sayHello{
    NSLog(@"hello world");
}
@end
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容