重写构造方法实现两种功能
来源:互联网 发布:股票行情软件免费下载 编辑:程序博客网 时间:2024/06/10 05:01
- 实现-instancetypeinitWithXXXintage
- 要求使每个新创建出来的对象都有一个自定义的默认值
实现-(instancetype)initWithXXX:(int)age;
思考&实现:创建一个学生类Student,通过重写构造方法实现创建学生对象的时候,默认的年龄的值为指定的年龄
student.h#import <Foundation/Foundation.h>@interface Student : NSObject@property (nonatomic, assign)int age;-(instancetype) initWithAge:(int)age;+(instancetype)studentAgeWith:(int)age;@end
Student.mimport "Student.h"@implementation Student-(void)dealloc{ NSLog(@"Student 被释放"); [super dealloc];}//自定义构造方法-(instancetype) initWithAge:(int)age{ if (self = [super init]){ _age = age; } return self;}//自定义初始化方法+(instancetype)studentAgeWith:(int)age{ return [[[self alloc] initWithAge:age]autorelease];}@end
main.m#import <Foundation/Foundation.h>#import "Student.h"int main(int argc, const char * argv[]){ @autoreleasepool{ Student * stu = [[[Student alloc]initWithAge:10]autorelease]; Student *stu1 = [Student studentWithAge:100]; NSLog(@"stu.age = %d, stu1.age = %d", stu.age, stu1.age); } reutrn 0;}
要求使每个新创建出来的对象都有一个自定义的默认值
student.h#import <Foundation/Foundation.h>@interface Student : NSObject@property (nonatomic, assign)int age;@end
Student.mimport "Student.h"@implementation Student-(instancetype)init{ if (self = [super init]){ _age = 10; //设置该变量的默认值 } return self; }@end
0 0
- 重写构造方法实现两种功能
- 重写父类方法的两种实现方式
- 菜单功能的两种实现方法
- 两种方法实现托盘功能
- android 实现分享功能两种方法
- 两种URL重写方法
- Comparable实现排序功能,重写排序方法
- 重写构造方法
- 重写构造方法
- 重写构造方法
- 重写构造方法
- iOS应用实现评论功能的两种方法
- iOS应用实现评论功能的两种方法
- iOS应用实现评论功能的两种方法
- 两种方法实现点击图片调用上传功能
- Object-c------重写构造方法
- 重写与重载,构造器,构造方法
- 方法重写、构造方法、方法重载
- #317 (div.2) D. Minimization
- UltraISO/Nero/Daemon Tools
- OCiOS开发:录音与音效
- (十)PHP正则表达式学习----测试工具的制作
- Android 性能分析案例
- 重写构造方法实现两种功能
- hive优化
- CustomView
- 字符串模式匹配--KMP之美
- 开源框架数据源配置
- 程序员谈网络改变我们的生活
- PNP管理器简析--基于ReactOS0.33
- storm trident实现单词计数
- House Robber