Objective-C一个简单类应该有哪些部分,何如写?

来源:互联网 发布:大数据时代与广告 编辑:程序博客网 时间:2024/04/27 14:39

首先还是以Book这个类为例子,下面分别是Book.h文件,Book.m文件,main.m文件,和实现结果.

Book.h文件
至于属性property里面的nonatomic,assign,retain什么含义点击打开链接有具体解释
#import <Foundation/Foundation.h>@interface Book : NSObject//创建两个属性name和author,创建属性后系统会自动生成setter和getter方法@property(nonatomic, retain)NSString * name;@property(nonatomic, retain)NSString * author;//指派初始化- (id)initWithName:(NSString *)name;- (id)initWithAuthor:(NSString *)author;- (id)initWithName:(NSString *)name Author:(NSString *)author;//便利构造器+ (id)bookWithName:(NSString *)name;+ (id)bookWithAuthor:(NSString *)author;+ (id)bookWithName:(NSString *)name Author:(NSString *)author;//dealloc 当对象引用计数器retaincount为0时 将调用dealloc销毁对象- (void)dealloc;//API- (void)bookByIntroduction;@end
Book.m文件
#import "Book.h"@implementation Book//指派初始化- (id)initWithName:(NSString *)name {    self = [self initWithName:name Author:nil];  //设置统一初始化入口    return self;}- (id)initWithAuthor:(NSString *)author {    self = [self initWithName:nil Author:author]; ////设置统一初始化入口    return self;}- (id)initWithName:(NSString *)name Author:(NSString *)author {    self = [super init];  //初始化父类对象给自己    if (self) {             //对象不为空        [self setName:name];  //setter方法存入对象        [self setAuthor:author];    }    return self;}//便利构造器+ (id)bookWithName:(NSString *)name {    Book * book = [[Book alloc] initWithName:name];    return [book autorelease];}+ (id)bookWithAuthor:(NSString *)author {    Book * book = [[Book alloc] initWithAuthor:author];    return [book autorelease];}+ (id)bookWithName:(NSString *)name Author:(NSString *)author {    Book * book = [[Book alloc] initWithName:name Author:author];    return [book autorelease];}- (void)dealloc {    [_name release]; //对象销毁时 将setter里的retain,release掉    [_author release];    [super dealloc];  //将init初始化中 继承的父类的对象销毁}//API- (void)bookByIntroduction {    NSLog(@"This book name is %@ and author is %@", _name, _author);}@end
main.m文件
#import <Foundation/Foundation.h>#import "Book.h"int main(int argc, const char * argv[]) {    @autoreleasepool {        Book * book = [Book bookWithName:@"吴承恩" Author:@"西游记"]; //便利构造器        [book bookByIntroduction];    }    return 0;}

0 0
原创粉丝点击