iOS之07-三大特性之多态 + NSString类

多态

 1、没有继承就没有多态

 2、代码体现:父类类型的指针指向子类对象

类的创建:

 1 #import <Foundation/Foundation.h>
 2 
 3 // 动物
 4 @interface Animal : NSObject
 5 - (void)eat;
 6 @end
 7 
 8 @implementation Animal
 9 - (void)eat {
10     NSLog(@"Animal-吃东西...");
11 }
12 @end
13 
14 //
15 @interface Dog : Animal
16 - (void)run;
17 @end
18 
19 @implementation Dog
20 
21 - (void)eat {
22     NSLog(@"Dog-吃东西...");
23 }
24 @end
25 
26 //
27 @interface Cat : Animal
28 @end
29 
30 @implementation Cat
31 - (void)eat {
32     NSLog(@"Cat-吃东西...");
33 }
34 @end

多态的实现:

int main() {
    // 多态:父类指针指向子类对象
    Animal *a = [Dog new];

    // 调用方法时会动态检测对象的真实形象
    [a eat];

    return 0;
}

  系统在调用方法时,会动态检测对象的真实形象

 3.好处:如果函数/方法参数中使用的父类类型,可以传入父类、子类对象,用于整合相似的函数

 4.局限性

    父类类型的指针变量 不能 直接调用子类特有的方法,必须强转为子类类型后,才能直接调用。虽然能够成功,但是编程规范不提倡

NSString

 1 #import <Foundation/Foundation.h>
 2 
 3 int main() {
 4     
 5     NSString *str = @"itcast";
 6     NSLog(@"%@", str);// %@ 是NSString类型的占位符
 7     
 8     int age = 15;
 9     int no = 5;
10     
11     NSString *name = @"哈哈jack";
12     int size = [name length]; // length方法计算的是字数
13     
14     NSLog(@"%d", size);
15     
16     // 创建OC字符串的另一种方式
17     NSString *newStr = [NSString stringWithFormat:@"My age is %d and no is %d and name is %@", age, no, name]; //stringWithFormat方法是转化字符串的格式
18     
19     NSLog(@"%@", newStr);
20     NSLog(@"%ld", [newStr length]);
21     
22     NSLog(@"My age is %d and no is %d and name is %@", age, no, name);
23     
24     return 0;
25 }

 %@所有对象类型占位符,也是NSString类型的占位符

 length方法是NSString中的一个对象方法( - ),主要用于计算字符串的字数

 stringWithFormat方法是NSString中的一个类方法( + ),主要是转换字符串的格式,用于创建OC字符串

posted @ 2016-03-19 19:30  墨隐于非  阅读(255)  评论(0编辑  收藏  举报