Objective-C学习笔记(二)——OC基本语法概述

来源:互联网 发布:微软数据库认证有用吗 编辑:程序博客网 时间:2024/06/05 06:05
1.源代码文件扩展名对比
                     头文件      实现文件
C语言             .h             .c
C++语言        .h             .cpp
OC语言          .h             .m
OC&C++       .h             .mm


3.类的声明,注意和Java区别,这里类的声明使用interface,而不是Class;以@interface开头,以@end结尾;类名是SimpleClass,继承自NSObject;
@interface SimpleClass:NSObject

@end


4.类的属性声明,属性以@property开头,(readonly)表示是只读的;
@interface Person:NSObject

@property NSString *firstName;
@property NSString *lastName;

@property NSNumber *yearOfBirth;
@property int yearOfBirth;

@property (readonly) NSString *sex;

@end


5.OC中的方法总共分为两种:

减号方法(普通方法又称对象方法)声明,可以理解为Java中的普通的方法,可以用对象进行调用;

加号方法(类方法,又称静态方法)声明,可以理解为Java中用static修饰的方法;


6.减号方法(普通方法又称对象方法)声明:
@interface Person : NSObject

-(void)someMethod;
-(void)someMethodWithValue:(SomeType)value;
-(void)someMethodWithFirstValue:(SomeType)info1 secondValue:(AnotherType)info2;

@end


7.加号方法(类方法,又称静态方法)声明:
@interface NSString : NSObject
+(id)string;
+(id)stringWithString:(NSString *)aString;
+(id)stringWithFormat:(NSString *)foramt,...;
+(id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error;
+(id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc;
@end


8.类的实现;类的实现用@implementation开头;
#import "XYZPerson.h"
@implementation XYZPerson

@end



9.完整的例子,import表示引入头文件;NSLog表示打印信息;

XYZPerson.h文件
@interface XYZPerson:NSObject
-(void)sayHello;
@end


XYZPerson.m文件
#import "XYZPerson.h"
@implementation XYZPerson
-(void)sayHello{
NSLog(@"Hello,World");

}


本文参考慕课网课程《征战Objective-C》。感谢!

3 0