zoukankan      html  css  js  c++  java
  • (Object-C)学习笔记(三) --OC的内存管理、封装、继承和多态

    OC的内存管理

      iOS7以前使用的是MRC手动内存管理,现在都使用ARC自动内存管理,一般不会出现内存泄漏问题。

    封装

      封装就是有选择的保护自己的代码。将给别人使用的接口留出来让人看见,其他的都隐藏起来。增加了代码的可读性、可维护性、可拓展性。

      将给别人看的代码放在 interface当中(.h or .m),不让看的放在implementation当中。这就是封装对象。

    继承

      子类可以继承父类非私有的属性和方法。

    继承的优点:1.代码复用 2.制定规则 3.为了多态

    继承的缺点:1.提高了代码的复杂性,维护性和复杂性降低 2.破坏了类的封装性 (老师说如果不是为了多态一般少用继承)

    例子:

    TRAnimal.h

    1 #import <Foundation/Foundation.h>
    2 
    3 @interface TRAnimal : NSObject
    4 @property NSString *name;
    5 @property int age;
    6 -(id)initWithName:(NSString*)name andAge:(int)age;
    7 -(void)eat;
    8 -(void)sleep;
    9 @end
    TRAnimal.m
     1 #import "TRAnimal.h"
     2 
     3 @implementation TRAnimal
     4 -(id)initWithName:(NSString *)name andAge:(int)age
     5 {
     6     if (self = [super init])
     7     {
     8         self.name = name;
     9         self.age = age;
    10     }
    11     return self;
    12 }
    13 -(void)eat
    14 {
    15     NSLog(@"动物%@吃", self.name);
    16 }
    17 -(void)sleep
    18 {
    19     NSLog(@"动物%@睡", self.name);
    20 }
    21 @end
    TRDog.h
    1 #import "TRAnimal.h"
    2 
    3 @interface TRDog : TRAnimal
    4 @property int weight;
    5 -(id)initWithName:(NSString *)name andAge:(int)age andWeight:(int)weight;
    6 -(void)watchHome;
    7 @end
    TRDog.m
     1 #import "TRDog.h"
     2 
     3 @implementation TRDog
     4 -(id)initWithName:(NSString *)name andAge:(int)age andWeight:(int)weight
     5 {
     6     if (self = [super initWithName:name andAge:age])
     7     {
     8         self.weight = weight;
     9     }
    10     return self;
    11 }
    12 -(void)watchHome
    13 {
    14     NSLog(@"狗狗%@正在看家", self.name);
    15 }
    16 -(void)eat
    17 {
    18     [super eat];
    19     NSLog(@"狗狗%@在啃骨头", self.name);
    20 }
    21 @end
    在狗类里我重写了eat方法,并且添加了watchHome方法。

    方法的重写:

      子类满足与父类的方法名相同、参数类型相同、返回值相同就是重写父类的方法。如果重写了父类方法就优先调用子类的方法,否则调用父类的方法。

    多态

      多态就是父类使用子类的构造方法。详细请看:http://www.cnblogs.com/wendingding/p/3705428.html

      

    We're here to put a dent in the universe!code改变世界!-----------------------------------------------------by.不装b就无法活下去的晨曦
  • 相关阅读:
    Run UliPad 4.1 Under Windows 7 64bit and wxPython 3.0.2
    Ubuntu下编译SuiteSparse-4.4.1和METIS-4.0.3
    Call Paralution Solver from Fortran
    Python调用C/Fortran混合的动态链接库-下篇
    调用gluNurbsCurve绘制圆弧
    glutBitmapCharacter及glBitmap在ATI显卡下无法正常显示的原因初探
    PyOpenGL利用文泉驿正黑字体显示中文字体
    图论常用算法之二 算法模板及建模总结
    图论常用算法之一 POJ图论题集【转载】
    通过身边小事解释机器学习是什么?
  • 原文地址:https://www.cnblogs.com/firstaurora/p/5189806.html
Copyright © 2011-2022 走看看