OC 类的继承

来源:互联网 发布:淘宝双十一广告视频 编辑:程序博客网 时间:2024/04/29 23:59
</pre><p></p><p></p><pre name="code" class="objc">////  main.m//  继承////  Created by LiuWei on 15/4/13.//  Copyright (c) 2015年 LiuWei. All rights reserved.//#import <Foundation/Foundation.h>/*继续的好处 抽取代码 建立类之间的关系 子类中拥有父类中所有的成员变量和方法 注意 基本上所有的类都继续自NSObject*/// Animal@interface Animal : NSObject{    int _age;    float _weight;}- (void)setAge: (int)age;- (void)setWeight: (float)weight;- (void)showInfo;@end// Dog@interface Dog : Animal@end// Cat@interface Cat : Animal@endint main(int argc, const char * argv[]) {       Dog *d = [Dog new];    [d setAge:5];    [d setWeight:12];    [d showInfo];        Cat *c = [Cat new];    [c setAge:2];    [c setWeight:2.5];    [c showInfo];        return 0;}@implementation Animal- (void)setAge: (int)age{    _age = age;}- (void)setWeight: (float)weight{    _weight = weight;}- (void)showInfo{    NSLog(@"age = %i, weight = %f", _age, _weight);}@end@implementation Dog@end@implementation Cat@end



根类 NSObject

NSObject is the root class of most Objective-C class hierarchies. Through NSObject,objects inherit a basic interface to the runtime system and the ability to behave as Objective-C objects.

NSObject 是大多数OC类继承的根类,通过继承NSObject, 作为OC对象则拥有了运行时系统和基本接口的能力


类方法 new


  • + new

    Allocates a new instance of the receiving class, sends it aninit message, and returns the initialized object.
    分配所接收类的一个新实现,并发送一条init消息,返回初始化过的对象

    Declaration
  • 声明
    SWIFT
    class funcnew() -> Self

    OBJECTIVE-C
    + (instancetye)new


    Return Value 返回值
    A new instance of the receiver.  所要接收的一个新实例

    Discussion 讨论
    This method is a combination of alloc andinit. Likealloc, it initializes theisa instance variable of the new object so it points to the class data structure. It then invokes theinit method to complete the initialization process. 这个方法结合了alloc和init. 像alloc一样,它初始化了新对象的isa实例变量,以指向类数据结构。然后它调用init方法来完成初始化过程

    Import Statement 导入语句
    OBJECTIVE-C
    @import ObjectiveC;


    SWIFT
    import ObjectiveC



    Availability 适用平台
    Available in iOS 2.0 and later. IOS2.0及以后版本







0 0
原创粉丝点击