您的位置:首页 > 职场人生

黑马程序员——ios学习笔记 OC self&异常

2015-08-06 23:13 447 查看

------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

1 self与super

① self调用自己方法,super调用父类方法

② self是类,super是预编译指令

③ [self class]和[super class]输出是一样的

//Person.h
//person类的申明
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
NSString *name;
int age;
}
-(void)setName:(NSString *)name andAge:(int)age;

+(void)showMessage;
@end

//Person.m
//person类的实现
#import "Person.h"

@implementation Person
-(void)setName:(NSString *)name andAge:(int)age{
// _name=name; 当实例变量与形参不同是可以直接赋值
// _age=age;
self.name=name; //当实例变量与形参相同则使用self赋值
self.age=age;
}

+(void)printInfo{
NSLog(@"Hello,World!");
}

+(void)showMessage{
[self printInfo]; //使用self调用类方法
}
@end

//main.m
//主函数源文件
#import <Foundation/Foundation.h>
#import "Person.h"

int main(int argc, const char * argv[]) {

Person *p=[[Person alloc]init];
[p setName:@"Kenshin" andAge:28];
[Person showMessage];

return 0;

2 异常处理

    Object-C语言的异常处理符号和C++、JAVA相似。可使用NSException,NSError或者自定义的类。异常处理机制是由这个四个关键字支持的:@try,@catch,@thorw,@finally。

    捕获异常:

@try{      }

@catch(NSException*exception){        }

@finally{       }

抛出异常(@throw):

NSException*exception = 

[NSException exceptionWithName: @“helloworldException"reason: @”illegal words” userInfo:nil];

@throwexception;

例如:

helloworld *h = [[helloworld alloc] init];
@try{
[h saysomething];
}
@catch(NSException*exception)
{
NSLog(@"main: Caught %@: %@", [exceptionname], [exceptionreason]);
}
@finally{
[h release];
}

总结:

self在对象中指代的是对象本身,self在类中指代的是类本身。故一个类中拥有同名的对象方法与类方法也不会调用出错。

异常处理用于设置可能出错的代码段,进行异常捕捉,便于代码的调试与修改。

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: