字符串
NSString *name = @"jikexueyuan";
以’%@’代表对象
NSLog(@"Hello Objective-C");
NSLog(@"The number is %d",1000);
NSLog(@"Hello %s","XiaoLi");
NSLog(@"Hello %@",name);
NSLog(@"ObjC Object %@",[[[NSObject alloc] init] description]); //实际上是调用NSObject中的description方法
Class的构成
.h file
1 | @interface People : NSObject{ |
.m file
1 | +(People*)peopleWithAge:(int)age andName:(NSString *)name{ |
call method
Hello *h = [[Hello alloc] init];
[h sayHello];
数组与字典
非可变数组
//三种构造方法,可以从plist文件中获取数据
NSArray *arr = @[@"Hello",@"jikexueyuan"];
NSArray *arr = [NSArray arrayWithObjects:@"Hello", @"jikexueyuan",nil];
NSArray *arr = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]];
for (int i=0; i<[arr count]; i++) {
NSLog(@"%@",[arr objectAtIndex:i]);
}
可变数组
NSMutableArray *arr = [[NSMutableArray alloc] init];
for (int i=0; i<100; i++) {
[arr addObject:[NSString stringWithFormat:@"Item %d",i]];
}
NSLog(@"%@",arr);
数组的plist文件
字典的plist文件
字典与可变字典
//字典的构造
NSDictionary *dict = @{@"name": @"ZhangSan",@"sex":@"male"};
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]];
NSLog(@"%@",[dict objectForKey:@"age"]);
//可变字典
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:@"jikexueyuan" forKey:@"name"];
NSLog(@"%@",[dict objectForKey:@"name"]);
protocol
.h file
#import <Foundation/Foundation.h>
@protocol IPeople <NSObject>
-(int)getAge;
-(void)setAge:(int)age;
-(NSString*)getName;
@end
.m file
@interface Man : NSObject<IPeople>{
int _age;
}
-(id)init;
-(void)setAge:(int)age;
-(NSString*)getName;
-(int)getAge;
@property id<ManDelegate> delegate;
@end
Exception
@try {
//需要被捕获异常的代码
@throw [NSException exceptionWithName:@"My Error" reason:nil userInfo:nil];
}
@catch (NSException *exception) {
//输出一场信息
NSLog(@"%@",exception);
}
@finally {
//无论是否有异常,都要执行
NSLog(@"run");
}